﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Windows;
using System.Windows.Forms;
using System.Xml;
using System.IO;

using Autodesk.Windows;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.Interop;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.EditorInput;
using WlanDesign;
using System.Runtime.InteropServices;
using System.Windows.Media.Imaging;

namespace WlanDesignDll
{
    public class AcadWlan
    {
        static string LayerFloorboundary = "楼层边界";//存放边界框的图层
        static string LayerLittleboundary = "楼层小边界";
        static string Layerline = "ZCLine";
        static string LayerHatch = "ZCHatch";
        static string LayerBuild = "0";
        static string LayerCircle = "ZCCircle";
        static string LayerExplode = "ZCExplode";
        [CommandMethod("AddToolBar")]
        public void AddToolBar()
        {
            //获取当前运行的程序集
            System.Reflection.Module myModule = System.Reflection.Assembly.GetExecutingAssembly().GetModules()[0];
            //获取当前运行的程序集的完整路径（包含文件名）
            string modulePath = myModule.FullyQualifiedName;
            //获取去除文件名后程序集的路径，即程序集所在的文件夹
            modulePath = modulePath.Substring(0, modulePath.LastIndexOf("\\"));
            //COM方式获取AutoCAD应用程序对象
            AcadApplication acadApp = (AcadApplication)Autodesk.AutoCAD.ApplicationServices.Application.AcadApplication;
            //获取当前菜单组，用于加入工具栏
            AcadMenuGroup currMenuGroup = acadApp.MenuGroups.Item(0);
            //为AutoCAD添加一个新的工具栏，并设置标题为"我的工具栏"
            AcadToolbar tbModify = currMenuGroup.Toolbars.Add("我的工具栏");
            //在新建的工具栏中添加一个"AP"按钮，以调用AP命令
            AcadToolbarItem button0 = tbModify.AddToolbarButton("", "AP", "添加无线接入点", "_Copy", Type.Missing);
            //设置AP按钮的图片
            button0.SetBitmaps(modulePath + "\\Resources\\ap.bmp", modulePath + "\\Resources\\ap.bmp");
            //'添加一个"功分器"按钮，以调用功分器命令
            AcadToolbarItem button1 = tbModify.AddToolbarButton("", "功分器", "添加功分器", "_Erase", Type.Missing);
            //设置功分器按钮的图片
            button1.SetBitmaps(modulePath + "\\Resources\\gfq.bmp", modulePath + "\\Resources\\gfq.bmp");
            //添加一个"合路器"按钮，以调用合路器命令
            AcadToolbarItem button2 = tbModify.AddToolbarButton("", "合路器", "添加合路器", "_Move", Type.Missing);
            //设置合路器按钮的图片
            button2.SetBitmaps(modulePath + "\\Resources\\hlq.bmp", modulePath + "\\Resources\\hlq.bmp");
            //添加一个"耦合器"按钮，以调用耦合器命令
            AcadToolbarItem button3 = tbModify.AddToolbarButton("", "耦合器", "添加耦合器", "_Rotate ", Type.Missing);
            //设置耦合器按钮的图片
            button3.SetBitmaps(modulePath + "\\Resources\\ohq.bmp", modulePath + "\\Resources\\ohq.bmp");
            //添加一个"天线"按钮，以调用天线命令
            AcadToolbarItem button4 = tbModify.AddToolbarButton("", "天线", "添加天线对象", "_Rotate ", Type.Missing);
            //设置天线按钮的图片
            button4.SetBitmaps(modulePath + "\\Resources\\tx.bmp", modulePath + "\\Resources\\tx.bmp");

            //添加一个弹出按钮，该按钮只用来附着下面的画图工具栏
            AcadToolbarItem FlyoutButton = tbModify.AddToolbarButton("", "画图工具", "画图工具", " ", true);
            //创建第二个工具栏。该工具栏将通过弹出按钮附加到第一个工具栏。
            AcadToolbar tbDraw = currMenuGroup.Toolbars.Add("画图工具栏");
            //下面的语句分别在工具栏上设置绘制圆、直线、多段线、矩形的按钮
            AcadToolbarItem button5 = tbDraw.AddToolbarButton("", "圆", "用指定半径创建圆", "_Circle ", Type.Missing);
            button5.SetBitmaps(modulePath + "\\Resources\\Circle.bmp", modulePath + "\\Resources\\Circle.bmp");
            AcadToolbarItem button6 = tbDraw.AddToolbarButton("", "直线", "创建直线段", "_Line ", Type.Missing);
            button6.SetBitmaps(modulePath + "\\Resources\\Line.bmp", modulePath + "\\Resources\\Line.bmp");
            AcadToolbarItem button7 = tbDraw.AddToolbarButton("", "多段线", "创建二维多段线", "_Pline ", Type.Missing);
            button7.SetBitmaps(modulePath + "\\Resources\\Polyline.bmp", modulePath + "\\Resources\\Polyline.bmp");
            AcadToolbarItem button8 = tbDraw.AddToolbarButton("", "矩形", "创建矩形多段线", "_Rectangle ", Type.Missing);
            button8.SetBitmaps(modulePath + "\\Resources\\Rectangle.bmp", modulePath + "\\Resources\\Rectangle.bmp");
            //将第二个工具栏附着到第一个工具栏的弹出按钮上
            FlyoutButton.AttachToolbarToFlyout(currMenuGroup.Name, tbDraw.Name);
            //显示第一个工具栏
            tbModify.Visible = true;
            //隐藏第二个工具栏
            tbDraw.Visible = false;
        }

        //增加自定义菜单WLAN
        [CommandMethod("AddMenuCom")]
        public static void AddMenuCom()
        {
            AcadApplication acadApp = (AcadApplication)Marshal.GetActiveObject("AutoCAD.Application.18");
            acadApp.Visible = true;
            AcadMenuBar menuBar = acadApp.MenuBar;
            AcadMenuGroup menuGroup = acadApp.MenuGroups.Item(0);
            AcadPopupMenus menus = menuGroup.Menus;
            //增加主菜单“WLAN”
            
            AcadPopupMenu mymenu = menus.Add("WLAN");
            //增加“WLAN”的子菜单“图纸管理”
            AcadPopupMenu menage = mymenu.AddSubMenu(0, "图纸管理");
            menage.AddMenuItem(0, "属性设置", "AttributeSet ");
            menage.AddMenuItem(1, "楼层设置", "BuildingSet ");
            menage.AddMenuItem(2, "衰减度设置", "SubAttributeSet ");
            //增加“WLAN”的子菜单“覆盖分析”
            mymenu.AddMenuItem(2, "覆盖分析", "ScanAnalyze ");//TestOn 
            //增加“WLAN”的子菜单“图纸导出”
            mymenu.AddMenuItem(3, "图纸导出", "DrawingExport ");
            //增加“WLAN”的子菜单“场强查看”
            mymenu.AddMenuItem(1, "场强查看", "TestOn ");
      
            mymenu.InsertInMenuBar(menuBar.Count - 2);
        }
        
        [CommandMethod("AttributeSet")]
        public static void AttributeSet()
        {
            //bool ret;
            //System.Threading.Mutex m = new System.Threading.Mutex(true, System.Windows.Forms.Application.ProductName, out   ret);
            //if (ret)
            //{
                // 获得当前文档和数据库   Get the current document and database
                //Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
                //Database acCurDb = acDoc.Database;
                //using (DocumentLock acLckDoc = acDoc.LockDocument())
                //{
                    //System.Windows.Forms.Application.EnableVisualStyles();   //这两行实现   XP   可视风格 
                    //System.Windows.Forms.Application.DoEvents(); 
            FormAttributeSet form = new FormAttributeSet();
            form.Show();
                    //System.Windows.Forms.Application.Run(new FormAttributeSet());
                //}
                //   frmMain   为你程序的主窗体，如果是控制台程序不用这句 
                //m.ReleaseMutex();
            //}
            //else
            //{
                //MessageBox.Show(null, "有一个和本程序相同的应用程序已经在运行，请不要同时运行多个本程序。\n\n这个程序即将退出。 ", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                //   提示信息，可以删除。 
                //Application.Exit();//退出程序 
            //} 
        }

        [CommandMethod("SubAttributeSet")]
        public static void SubAttributeSet()
        {
            DialogResult dresult = MessageBox.Show("请选择对象！");
            
            Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Database acCurDb = acDoc.Database;
            // ini文件与当前文档在同一目录下，并且名字相同
            string[] name = acDoc.Name.Split('.');
            string iniName = name[0] + ".ini";

            string biuldLyr = ReadIniTxt(iniName, "layer", "building_layer");// 建筑物图层

            Entity acEnt = null;
            bool flag = true;
            while (flag)
            {
                using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
                {
                    // 以只读方式打开块表记录   Open the Block table record for read
                    BlockTable acBlkTbl;
                    acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId, OpenMode.ForRead) as BlockTable;
                    // 以写方式打开模型空间块表记录   Open the Block table record Model space for write
                    BlockTableRecord acBlkTblRec;
                    acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForRead) as BlockTableRecord;
                    PromptEntityOptions peo = new PromptEntityOptions("\n请选择对象：");
                    PromptEntityResult per = acDoc.Editor.GetEntity(peo);
                    if (per.Status != PromptStatus.OK) flag = false;

                    else
                    {
                        //PromptEntityResult p = acDoc.Editor.GetEntity("请选择对象：");
                        //if (p == null)
                        //{ return; }
                        acEnt = acTrans.GetObject(per.ObjectId, OpenMode.ForRead) as Entity;
                        // 判断选择的是否为建筑物
                        if (acEnt.Layer == biuldLyr)
                        {
                            flag = false;
                            // 写入ini文件

                            WriteIniTxt(iniName, "handle", "handlevalue", acEnt.Handle.Value.ToString());
                        }
                        else { flag = true; MessageBox.Show("您选择的对象不是建筑物，请重新选择！"); }
                    }
                }
            }

            // 判断是否有选中实体
            //Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            //string entId1 = ReadIniTxt(iniName, "handle", "handlevalue");
            if (acEnt!=null)
            {
                //long enth = long.Parse(entId1);

                //Handle entId = new Handle(enth);

                //bool ret;
                //System.Threading.Mutex m = new System.Threading.Mutex(true, System.Windows.Forms.Application.ProductName, out   ret);
                //if (ret)
                //{
                    System.Windows.Forms.Application.Run(new FormAttenuationSetSub1());
                    //WriteIniTxt(iniName, "handle", "handlevalue", "null");
                    //   frmMain   为你程序的主窗体，如果是控制台程序不用这句 
                    //m.ReleaseMutex();
                //}
                //else
                //{
                //}
            }
            else
            {
            }
            //WriteIniTxt(iniName, "handle", "handlevalue", "");
        }

        // 增加WLAN快捷菜单
        [CommandMethod("AddApplicationMenuWLAN")]
        public void Initialize()
        {
            // We defer the creation of our Application Menu to when
            // the menu is next accessed
            ComponentManager.ApplicationMenu.Opening += new EventHandler<EventArgs>(ApplicationMenu_Opening);
        }

        public void ApplicationMenu_Opening(object sender, EventArgs e)
        {
            // Remove the event when it is fired
            ComponentManager.ApplicationMenu.Opening -= new EventHandler<EventArgs>(ApplicationMenu_Opening);

            // Add our Application Menu
            AddApplicationMenuItemWLAN();
        }

        public void AddApplicationMenuItemWLAN()
        {
            //获取应用菜单
            Autodesk.Windows.ApplicationMenu acAppMenu = Autodesk.Windows.ComponentManager.ApplicationMenu;

            //加入分类线
            Autodesk.Windows.RibbonSeparator acRs = new RibbonSeparator();
            //acAppMenu.MenuContent.Items.Add(acRs);

            //增加主菜单“WLAN”
            Autodesk.Windows.ApplicationMenuItem acAppMenuIt0 = new Autodesk.Windows.ApplicationMenuItem();
            acAppMenuIt0.Text = "WLAN";
            acAppMenuIt0.Description = "WLAN工程图纸辅助设计";
            acAppMenuIt0.LargeImage = GetIcon("\\Resources\\1.ico");
            
            //增加“WLAN”的子菜单“图纸管理”
            Autodesk.Windows.ApplicationMenuItem acAppMenuIt00 = new Autodesk.Windows.ApplicationMenuItem();
            acAppMenuIt00.Text = "图纸管理";
            acAppMenuIt00.Description = "图纸分析前的初始化";
            acAppMenuIt00.LargeImage = GetIcon("\\Resources\\guanli.ico");
            //增加“图纸管理”的子菜单“属性设置”
            Autodesk.Windows.ApplicationMenuItem acAppMenuIt000 = new Autodesk.Windows.ApplicationMenuItem();
            acAppMenuIt000.Text = "属性设置";
            acAppMenuIt000.LargeImage = GetIcon("\\Resources\\Run.ico");
            acAppMenuIt000.CommandHandler = new AttibuteSetCommandHandler();
            acAppMenuIt00.Items.Add(acAppMenuIt000);
            //增加“图纸管理”的子菜单“楼层设置”
            Autodesk.Windows.ApplicationMenuItem acAppMenuIt001 = new Autodesk.Windows.ApplicationMenuItem();
            acAppMenuIt001.Text = "楼层设置";
            acAppMenuIt001.LargeImage = GetIcon("\\Resources\\Pause.ico");
            acAppMenuIt001.CommandHandler = new BuildingSetCommandHandler();
            acAppMenuIt00.Items.Add(acAppMenuIt001);
            //增加“图纸管理”的子菜单“衰减度设置”
            Autodesk.Windows.ApplicationMenuItem acAppMenuIt002 = new Autodesk.Windows.ApplicationMenuItem();
            acAppMenuIt002.Text = "衰减度设置";
            acAppMenuIt002.LargeImage = GetIcon("\\Resources\\shuaijian.ico");
            acAppMenuIt002.CommandHandler = new SubAttenuationSetCommandHandler();
            acAppMenuIt00.Items.Add(acAppMenuIt002);

            acAppMenuIt0.Items.Add(acAppMenuIt00);

            //增加“WLAN”的子菜单“覆盖分析”
            Autodesk.Windows.ApplicationMenuItem acAppMenuIt01 = new Autodesk.Windows.ApplicationMenuItem();
            acAppMenuIt01.Text = "覆盖分析";
            acAppMenuIt01.Description = "画出天线的覆盖范围";
            acAppMenuIt01.LargeImage = GetIcon("\\Resources\\fugai.ico");
            acAppMenuIt01.CommandHandler = new ScanAnalyzeCommandHandler();
            acAppMenuIt0.Items.Add(acAppMenuIt01);

            //增加“WLAN”的子菜单“图纸导出”
            Autodesk.Windows.ApplicationMenuItem acAppMenuIt02 = new Autodesk.Windows.ApplicationMenuItem();
            acAppMenuIt02.Text = "图纸导出";
            acAppMenuIt02.Description = "导出每个楼层的jpg图片";
            acAppMenuIt02.LargeImage = GetIcon("\\Resources\\Picture.ico");
            acAppMenuIt02.CommandHandler = new DrawingExportCommandHandler();
            acAppMenuIt0.Items.Add(acAppMenuIt02);

            //增加“WLAN”的子菜单“场强查看”
            Autodesk.Windows.ApplicationMenuItem acAppMenuIt03 = new Autodesk.Windows.ApplicationMenuItem();
            acAppMenuIt03.Text = "场强查看";
            acAppMenuIt03.Description = "进行覆盖分析后，鼠标悬于覆盖区域显示场强";
            acAppMenuIt03.LargeImage = GetIcon("\\Resources\\changqiang.ico");
            acAppMenuIt03.CommandHandler = new FeildStrCommandHandler();
            acAppMenuIt0.Items.Add(acAppMenuIt03);

            /*
            //增加“WLAN”的子菜单“系统配置”
            Autodesk.Windows.ApplicationMenuItem acAppMenuIt03 = new Autodesk.Windows.ApplicationMenuItem();
            acAppMenuIt03.Text = "系统配置";

            //增加“系统配置”的子菜单“网络配置”
            Autodesk.Windows.ApplicationMenuItem acAppMenuIt030 = new Autodesk.Windows.ApplicationMenuItem();
            acAppMenuIt030.Text = "网络配置";
            acAppMenuIt03.Items.Add(acAppMenuIt030);
            //增加“系统配置”的子菜单“数据下载”
            Autodesk.Windows.ApplicationMenuItem acAppMenuIt031 = new Autodesk.Windows.ApplicationMenuItem();
            acAppMenuIt031.Text = "数据下载";
            acAppMenuIt03.Items.Add(acAppMenuIt031);
            //增加“系统配置”的子菜单“修改密码”
            Autodesk.Windows.ApplicationMenuItem acAppMenuIt033 = new Autodesk.Windows.ApplicationMenuItem();
            acAppMenuIt033.Text = "修改密码";
            acAppMenuIt03.Items.Add(acAppMenuIt033);

            acAppMenuIt0.Items.Add(acAppMenuIt03);
             */

            //acAppMenu.MenuContent.Items.Add(acAppMenuIt0);
            acAppMenu.MenuContent.Items.Insert(acAppMenu.MenuContent.Items.Count - 1, acAppMenuIt0);
            acAppMenu.MenuContent.Items.Insert(acAppMenu.MenuContent.Items.Count - 1,acRs);
        }
        //
        public static System.Windows.Media.ImageSource GetIcon(string ico)
        {
            string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            string fileName = path + "\\" + ico;
            if (File.Exists(fileName))
            {
                // Get access to it via a stream
                Stream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
                using (fs)
                {
                    // Decode the contents and return them
                    IconBitmapDecoder dec = new IconBitmapDecoder(fs,
                    BitmapCreateOptions.PreservePixelFormat,
                    BitmapCacheOption.Default);


                    return dec.Frames[0];
                }
            }
            return null;
        }

        // 楼层设定
        [CommandMethod("BuildingSet")]
        public void BuildingSet()
        {
            Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Database acCurDb = acDoc.Database;
            //MessageBox.Show(acDoc.Name.Split('\\').Count().ToString ());
            if (acDoc.Name.Split('\\').Count() >= 2)
            {
                Editor acDocEd = acDoc.Editor;
                //string LayerFloorboundary = "Floorboundary";//存放边界框的图层
                string LayerFloorboundary = "楼层边界";//存放边界框的图层
                Point3d ptStart;
                Point3d ptEnd;
                try
                {
                    using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
                    {
                        // 以只读方式打开块表记录   Open the Block table record for read
                        BlockTable acBlkTbl;
                        acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId, OpenMode.ForRead) as BlockTable;
                        // 以写方式打开模型空间块表记录   Open the Block table record Model space for write
                        BlockTableRecord acBlkTblRec;
                        acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;
                        LayerTable acLyrTbl;
                        acLyrTbl = acTrans.GetObject(acCurDb.LayerTableId, OpenMode.ForRead) as LayerTable;
                        if (acLyrTbl.Has(LayerFloorboundary) == false)
                        {
                            LayerTableRecord acLyrTblRec = new LayerTableRecord();
                            acLyrTblRec.Name = LayerFloorboundary;
                            acLyrTbl.UpgradeOpen();
                            acLyrTbl.Add(acLyrTblRec);
                            acTrans.AddNewlyCreatedDBObject(acLyrTblRec, true);
                        }
                        MessageBox.Show("请在图纸中划定出楼层图形的边界！");
                        PromptPointResult pPResult = acDocEd.GetPoint("请选择范围的左上点");
                        if (pPResult.Status == PromptStatus.OK)
                        {
                            ptStart = pPResult.Value;

                            PromptPointResult pPResult2 = acDocEd.GetCorner("\n请选择范围的右下点", ptStart);
                            if (pPResult2.Status == PromptStatus.OK)
                            {
                                ptEnd = pPResult2.Value;
                                if (ptEnd.X > ptStart.X && ptEnd.Y < ptStart.Y)
                                {
                                    Point2d p0 = new Point2d(ptStart.X, ptStart.Y);
                                    Point2d p1 = new Point2d(ptStart.X, ptEnd.Y);
                                    Point2d p2 = new Point2d(ptEnd.X, ptEnd.Y);
                                    Point2d p3 = new Point2d(ptEnd.X, ptStart.Y);
                                    Polyline acPoly = new Polyline();
                                    acPoly.SetDatabaseDefaults();
                                    acPoly.AddVertexAt(0, p0, 0, 0, 0);
                                    acPoly.AddVertexAt(1, p1, 0, 0, 0);
                                    acPoly.AddVertexAt(2, p2, 0, 0, 0);
                                    acPoly.AddVertexAt(3, p3, 0, 0, 0);
                                    acPoly.AddVertexAt(4, p0, 0, 0, 0);
                                    acPoly.Closed = true;
                                    acPoly.Layer = LayerFloorboundary;
                                    // 添加新对象到块表记录和事务中   Add the new object to the block table record and the transaction
                                    acBlkTblRec.AppendEntity(acPoly);
                                    acTrans.AddNewlyCreatedDBObject(acPoly, true);
                                    palette(ptStart, ptEnd);
                                    System.Windows.Forms.Application.Run(new FormBuildingSet());

                                    // ini文件与当前文档在同一目录下，并且名字相同
                                    string[] name1 = acDoc.Name.Split('.');
                                    string iniName1 = name1[0] + ".ini";
                                    // 写入ini文件
                                    string floor = ReadIniTxt(iniName1, "floor", "building_floor");
                                    if (floor != "")
                                    {
                                        FloorName(ptStart, ptEnd, floor);
                                        WriteIniTxt(iniName1, "floor", "building_floor", "");
                                        acTrans.Commit();
                                    }
                                }
                                else
                                {
                                    MessageBox.Show("选择的范围无效！");
                                }
                            }
                        }
                    }
                }
                catch
                {
                    MessageBox.Show("楼层设定失败！");
                }
            }
            else
            {
                MessageBox.Show("请先保存图纸！");
            }
        }
        // 衰减度设定
        [CommandMethod("AttenuationSet")]
        public void AttenuationSet()
        { 
            Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Database acCurDb = acDoc.Database;
            // ini文件与当前文档在同一目录下，并且名字相同
            string[] name = acDoc.Name.Split('.');
            string iniName = name[0] + ".ini";

            string penet0 = ReadIniTxt(iniName, "attenuation", "penetrance_attenuation");//读取上次设置的衰减度
            string biuldLyr = ReadIniTxt(iniName, "layer", "building_layer");// 建筑物图层

            string[] name1 = acDoc.Name.Split('.');
            string iniName1 = name1[0] + ".ini";
            string penet1 = ReadIniTxt(iniName1, "attenuation1", "penetrance_attenuation1");//读取本次设定的衰减度
            // 设置对象属性


            using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
            {
                // 以只读方式打开块表记录   Open the Block table record for read
                BlockTable acBlkTbl;
                acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId, OpenMode.ForWrite) as BlockTable;
                // 以写方式打开模型空间块表记录   Open the Block table record Model space for write
                BlockTableRecord acBlkTblRec;
                acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;

                foreach (ObjectId acObjId in acBlkTblRec)
                {
                    Entity acEnt = acTrans.GetObject(acObjId, OpenMode.ForWrite) as Entity;
                    if (acEnt.Layer == biuldLyr)
                    {
                        var rb = acEnt.GetXDataForApplication("degreeofdecay");
                        if (rb == null)
                        {
                            var rat = acTrans.GetObject(acCurDb.RegAppTableId, OpenMode.ForWrite) as RegAppTable;
                            if (!rat.Has("degreeofdecay"))
                            {
                                var ratr = new RegAppTableRecord();
                                ratr.Name = "degreeofdecay";
                                rat.Add(ratr);
                                acTrans.AddNewlyCreatedDBObject(ratr, true);
                            }
                            ResultBuffer resb = new ResultBuffer(new TypedValue(1001, "degreeofdecay"), new TypedValue(1000, penet1));
                            acEnt.XData = resb;
                            resb.Dispose();
                        }
                        else
                        {
                            List<TypedValue> values = rb.Cast<TypedValue>().ToList();
                            //int value = Convert.ToInt32(values[1].Value);//读取透射衰减度，并把其转换为整型
                            //string value_1 = Convert.ToString(value);//将整型转换为字符串型
                            string value1 = Convert.ToString(values[1].Value);
                            if (value1 == penet0)
                            {
                                ResultBuffer resb = new ResultBuffer(new TypedValue(1001, "degreeofdecay"), new TypedValue(1000, penet1));
                                acEnt.XData = resb;
                                resb.Dispose();
                            }
                            if (value1 != penet0)
                            {
                                ResultBuffer resb = new ResultBuffer(new TypedValue(1001, "degreeofdecay"), new TypedValue(1000, value1));
                                acEnt.XData = resb;
                                resb.Dispose();
                            }
                        }
                    }                 
                }
                acTrans.Commit();
            }
        }
        //
        // Summery
        // 加载信息到ini文件
        //
        public static void WriteIniTxt(string sPath, string Section, string Key, string value)
        {
            string ServerName = value;

            IniFileRW ini = new IniFileRW(sPath);

            ini.IniWriteValue(Section, Key, ServerName);
        }
        //
        // Summery
        // 从ini文件读取信息
        //
        public static string ReadIniTxt(string sPath, string Section, string Key)
        {
            string ServerName;
            IniFileRW ini = new IniFileRW(sPath);
            ServerName = ini.IniReadValue(Section, Key);
            string strSql = ServerName;
            return strSql;
        }
        // 自定义衰减度设定
        [CommandMethod("AttenuationSetSub1")]
        public void AttenuationSetSub1()
        {
            Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Database acCurDb = acDoc.Database;
            string[] name1 = acDoc.Name.Split('.');
            string iniName1 = name1[0] + ".ini";
            string penet1 = ReadIniTxt(iniName1, "attenuationsub", "penetrance_attenuationsub");//读取原ini文件中所有的用户名组成的字符串
            string entId1 = ReadIniTxt(iniName1, "handle", "handlevalue");
            long enth=Convert.ToInt64(entId1);
            
            Handle entId = new Handle(enth);
            // 设置对象属性
            
            using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
            {
                // 以只读方式打开块表记录   Open the Block table record for read
                BlockTable acBlkTbl;
                acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId, OpenMode.ForRead) as BlockTable;
                // 以写方式打开模型空间块表记录   Open the Block table record Model space for write
                BlockTableRecord acBlkTblRec;
                acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;
                Entity acEnt = acTrans.GetObject(acCurDb.GetObjectId(false, entId, 0), OpenMode.ForWrite) as Entity;
                var rb = acEnt.GetXDataForApplication("degreeofdecay");
                if (rb == null)
                {
                    var rat = acTrans.GetObject(acCurDb.RegAppTableId, OpenMode.ForWrite) as RegAppTable;
                    if (!rat.Has("degreeofdecay"))
                    {
                        var ratr = new RegAppTableRecord();
                        ratr.Name = "degreeofdecay";
                        rat.Add(ratr);
                        acTrans.AddNewlyCreatedDBObject(ratr, true);
                    }

                }
                ResultBuffer resb = new ResultBuffer(new TypedValue(1001, "degreeofdecay"), new TypedValue(1000, penet1));
                acEnt.XData = resb;
                resb.Dispose();
                acTrans.Commit();
            }
        }
        /*
        // 自定义衰减度设定--选择对象
        [CommandMethod("AttenuationSetSub2")]
        public void AttenuationSetSub2()
        {
            Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Database acCurDb = acDoc.Database;
            Entity acEnt = null;
        
            using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
            {
                // 以只读方式打开块表记录   Open the Block table record for read
                BlockTable acBlkTbl;
                acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId, OpenMode.ForRead) as BlockTable;
                // 以写方式打开模型空间块表记录   Open the Block table record Model space for write
                BlockTableRecord acBlkTblRec;
                acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForRead) as BlockTableRecord;
                PromptEntityResult p = acDoc.Editor.GetEntity("请选择对象：");
                 acEnt = acTrans.GetObject(p.ObjectId, OpenMode.ForRead) as Entity;
                

            }
            string[] name1 = acDoc.Name.Split('.');
            string iniName1 = name1[0] + "子.ini";
            // 写入ini文件

            WriteIniTxt(iniName1, "handle", "handlevalue", acEnt.Handle.Value.ToString());
        }
         */

        // 图纸导出
        [CommandMethod("DrawingExport")]
        public void DrawingExport()
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            Editor ed = doc.Editor;

            //获取当前打开图形的路
            string[] name = doc.Name.Split('.');

            // 从ini文件获得区域的开始点和结束点

            string iniName1 = name[0] + ".ini";

            using (Transaction flooracTrans = db.TransactionManager.StartTransaction())
            {

                // 以只读方式打开块表   Open the Block table for read
                BlockTable flooracBlkTbl;
                flooracBlkTbl = flooracTrans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;

                // 以只读方式打开模型空间的块表记录    Open the Block table record Model space for read
                BlockTableRecord flooracBlkTblRec;
                flooracBlkTblRec = flooracTrans.GetObject(flooracBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForRead) as BlockTableRecord;
                foreach (ObjectId floorId in flooracBlkTblRec)
                {
                    Entity floorEnt = flooracTrans.GetObject(floorId, OpenMode.ForRead) as Entity;
                    if (floorEnt.Layer == LayerFloorboundary)
                    {
                        Polyline floorPl = flooracTrans.GetObject(floorEnt.ObjectId, OpenMode.ForRead) as Polyline;
                        Point3d ptFloorStart = floorPl.StartPoint;
                        Point3d ptFloorEnd = floorPl.GetPoint3dAt(2);

                        double floorLen = ptFloorStart.Y - ptFloorEnd.Y;
                        double length = (floorLen / 2) / 13;
                        double dis = length / 2;
                        double wid = ptFloorEnd.X - ptFloorStart.X;
                        double width = wid / 20;
                        Point3d ptStart = ptFloorStart;
                        Point3d ptEnd = new Point3d(ptFloorEnd.X + dis + 10 + 4 * width, ptFloorEnd.Y, 0);

                        /*
                        //选择矩形区域，获取矩形的两个对角点
                        //PromptPointResult pPResult = ed.GetPoint("选择起点");
                        string[] strStart = ReadIniTxt(iniName1, "drawingexport", "building_start").Remove(0, 1).Split(',');
                        Point3d ptStart = new Point3d(Convert.ToDouble(strStart[0]), Convert.ToDouble(strStart[1]), 0);

                        //PromptPointResult pPResult2 = ed.GetCorner("\n选择对角点", ptStart);
                        string[] strEnd = ReadIniTxt(iniName1, "drawingexport", "building_end").Remove(0, 1).Split(',');
                        Point3d ptEnd = new Point3d(Convert.ToDouble(strEnd[0]), Convert.ToDouble(strEnd[1]), 0);
                        //Point3d ptEnd = pPResult2.Value;
                         */
                        string floorname = "";
                        //启动一个事务
                        using (Transaction acTrans = db.TransactionManager.StartTransaction())
                        {

                            // 以只读方式打开块表   Open the Block table for read
                            BlockTable acBlkTbl;
                            acBlkTbl = acTrans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;

                            // 以只读方式打开模型空间的块表记录    Open the Block table record Model space for read
                            BlockTableRecord acBlkTblRec;
                            acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForRead) as BlockTableRecord;


                            //选择包含在框内部的所有实体
                            DBObjectCollection collectionInWindow = InWindow(ptStart, ptEnd, doc);

                            //将包含在框内部的实体复制到目标点
                            //List<Entity> ents = new List<Entity>();

                            foreach (Entity entity in collectionInWindow)
                            {

                                //ents.Add((Entity)entity.Clone());
                                //获取楼层名
                                //&& entity.GetType().Name == "DBText"
                                if (entity.Layer == "楼层名")
                                {
                                    DBText dbText = acTrans.GetObject(entity.ObjectId, OpenMode.ForRead) as DBText;
                                    floorname = dbText.TextString;
                                }
                            }
                        }
                        if (floorname != "")
                        {
                            // 获得楼层名
                            //string floorname = ReadIniTxt(iniName1, "drawingexport", "jpgfloor");
                            string jpgName = name[0] + "-" + floorname + ".jpg";
                            string[] imagetxts = jpgName.Split('\\');
                            string imagetxt = imagetxts[imagetxts.Count() - 1];

                            /*
                            <?xml version="1.0" encoding="UTF-8"?>
                            <building>
                                <floor>
                                    <name>一楼</name>
                                    <image>财经大厦-一楼.jpg</image>
                                    <transmitters>
                                        <transmitter>
                                            <name>全向吸顶天线-0</name>
                                            <num>ANT1-8F</num>
                                            <out>15.3</out>
                                            <x>54</x>
                                            <y>138</y>
                                        </transmitter>
                                        <transmitter>
                                        ……
                                        </transmitter>
                                        ……
                                    </transmitters>
                                </floor>
                                <floor>
                                ……
                                </floor>
                                ……
                            </building>

                             */
                            //创建XML
                            string xmlName = name[0] + ".xml";
                            XmlDocument xmldoc = new XmlDocument();
                            XmlNode root;

                            if (File.Exists(xmlName))//如果是文件的话
                            {
                                xmldoc.Load(xmlName);
                                root = (XmlNode)xmldoc.DocumentElement;
                            }
                            else
                            {
                                XmlDeclaration dec = xmldoc.CreateXmlDeclaration("1.0", "UTF-8", null);
                                xmldoc.AppendChild(dec);
                                //创建一个根节点（一级）
                                root = xmldoc.CreateElement("building");
                                xmldoc.AppendChild(root);
                            }
                            XmlNodeList list = xmldoc.SelectNodes("building/floor");
                            if (list.Count > 0)
                            {
                                foreach (XmlElement element in list)
                                {
                                    XmlElement xml = (XmlElement)element.SelectSingleNode("name");
                                    if (xml.InnerText == floorname)
                                    {
                                        element.ParentNode.RemoveChild(element);
                                    }
                                }
                            }

                            //创建节点floor
                            XmlElement floor = xmldoc.CreateElement("floor");
                            root.AppendChild(floor);
                            //创建节点name
                            XmlElement fname = xmldoc.CreateElement("name");
                            fname.InnerText = floorname;
                            floor.AppendChild(fname);
                            //创建节点image
                            XmlElement image = xmldoc.CreateElement("image");
                            image.InnerText = imagetxt;
                            floor.AppendChild(image);
                            //创建节点transmitters
                            XmlElement transmitters = xmldoc.CreateElement("transmitters");
                            floor.AppendChild(transmitters);

                            string transmitterLayer = ReadIniTxt(iniName1, "layer", "antenna_layer");
                            string[] transmitterLayerLt = transmitterLayer.Split(',');
                            //启动一个事务
                            using (Transaction acTrans = db.TransactionManager.StartTransaction())
                            {

                                // 以只读方式打开块表   Open the Block table for read
                                BlockTable acBlkTbl;
                                acBlkTbl = acTrans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;

                                // 以只读方式打开模型空间的块表记录    Open the Block table record Model space for read
                                BlockTableRecord acBlkTblRec;
                                acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForRead) as BlockTableRecord;

                                //选择包含在框内部的所有实体
                                DBObjectCollection collectionInWindow = InWindow(ptStart, ptEnd, doc);

                                //将包含在框内部的实体复制到目标点
                                List<Entity> ents = new List<Entity>();

                                foreach (Entity entity in collectionInWindow)
                                {
                                    ents.Add((Entity)entity.Clone());
                                    //获取天线（信号源）
                                    if (transmitterLayerLt.Contains(entity.Layer) && entity.GetType().Name == "BlockReference")
                                    {
                                        BlockReference blkRf = acTrans.GetObject(entity.ObjectId, OpenMode.ForRead) as BlockReference;
                                        //扩展属性
                                        AttributeCollection attCol = blkRf.AttributeCollection;
                                        string strnum = "";
                                        double douout = 0;
                                        foreach (ObjectId attId in attCol)
                                        {
                                            AttributeReference attRef = (AttributeReference)acTrans.GetObject(attId, OpenMode.ForRead);
                                            if (attRef.Tag == "NUM")
                                            {
                                                strnum = attRef.TextString;
                                            }

                                            foreach (ObjectId objectid in acBlkTblRec)
                                            {
                                                Entity acEnt = acTrans.GetObject(objectid, OpenMode.ForWrite) as Entity;
                                                if (acEnt.GetType().Name == "BlockReference")
                                                {
                                                    bool outFlag = false;
                                                    BlockReference blkRf0 = acTrans.GetObject(acEnt.ObjectId, OpenMode.ForRead) as BlockReference;
                                                    //扩展属性
                                                    AttributeCollection attCol0 = blkRf0.AttributeCollection;
                                                    //string strnum0 = "";
                                                    foreach (ObjectId attId0 in attCol0)
                                                    {
                                                        AttributeReference attRef0 = (AttributeReference)acTrans.GetObject(attId0, OpenMode.ForRead);
                                                        if (attRef0.Tag == "NUM" && attRef0.TextString == strnum)
                                                        {
                                                            outFlag = true;
                                                        }
                                                    }
                                                    if (outFlag)
                                                    {
                                                        //double d=0;
                                                        foreach (ObjectId attId0 in attCol0)
                                                        {
                                                            AttributeReference attRef1 = (AttributeReference)acTrans.GetObject(attId0, OpenMode.ForRead);
                                                            if (attRef1.Tag.Contains("OUT") && attRef1.TextString != "")
                                                            {
                                                                string str = attRef1.TextString;
                                                                str = str.Replace("/", "").Trim();
                                                                if (isNumberic(str))
                                                                {
                                                                    double dou = Convert.ToDouble(str);
                                                                    if (douout < dou) douout = dou;
                                                                }
                                                            }
                                                        }
                                                    }

                                                }
                                            }
                                        }

                                        //创建节点transmitter
                                        XmlElement transmitter = xmldoc.CreateElement("transmitter");
                                        transmitters.AppendChild(transmitter);
                                        //创建节点name
                                        XmlElement transmittername = xmldoc.CreateElement("name");
                                        transmittername.InnerText = blkRf.Name;
                                        transmitter.AppendChild(transmittername);
                                        //创建节点num
                                        XmlElement num = xmldoc.CreateElement("num");
                                        num.InnerText = strnum;
                                        transmitter.AppendChild(num);
                                        //创建节点out
                                        XmlElement xmlout = xmldoc.CreateElement("out");
                                        xmlout.InnerText = douout.ToString();
                                        transmitter.AppendChild(xmlout);
                                        Point3d position = blkRf.Position;
                                        //创建节点x
                                        XmlElement x = xmldoc.CreateElement("x");
                                        x.InnerText = (position.X - ptStart.X).ToString();
                                        transmitter.AppendChild(x);
                                        //创建节点y
                                        XmlElement y = xmldoc.CreateElement("y");
                                        y.InnerText = (position.Y - ptStart.Y).ToString();
                                        transmitter.AppendChild(y);

                                    }
                                }
                                xmldoc.Save(xmlName);
                                Console.Write(xmldoc.OuterXml);
                                MessageBox.Show(floorname+"的天线信息已保存到：\n" + xmlName);
                            }

                            //调用-plot命令
                            InvokeArx.Command(true, "-plot", "Y", "", "PublishToWeb JPG.pc3", "", "L", "N", "w",
                               ptStart, ptEnd,
                                "F", "", "Y", ".", "Y", "A", jpgName, "N", "Y");
                            MessageBox.Show(floorname+"的图片已保存到：\n" + jpgName);
                        }

                    }
                }
            }
            
        }
        /// <summary>
        /// 判断字符串是否为数字
        /// </summary>
        public static bool isNumberic(string message)
        {
            System.Text.RegularExpressions.Regex rex = new System.Text.RegularExpressions.Regex(@"^(-?\d+)(\.\d+)?$");
            if (rex.IsMatch(message))
            {
                return true;
            }
            else
                return false;
        }

        /// <summary>
        /// 选择包含在矩形区域内的实体
        /// </summary>
        /// <param name="pt1">矩形的左上角</param>
        /// <param name="pt2">矩形的右下角</param>
        /// <param name="doc">当前文档</param>
        /// <returns></returns>
        public static DBObjectCollection InWindow(Point3d pt1, Point3d pt2, Document doc)
        {
            Database db = doc.Database;
            Editor ed = doc.Editor;
            Entity entity = null;
            DBObjectCollection entityCollection = new DBObjectCollection();
            PromptSelectionResult ents = ed.SelectWindow(pt1, pt2);
            if (ents.Status == PromptStatus.OK)
            {
                using (Transaction trans = db.TransactionManager.StartTransaction())
                {
                    SelectionSet ss = ents.Value;
                    foreach (ObjectId id in ss.GetObjectIds())
                    {
                        entity = trans.GetObject(id, OpenMode.ForWrite, true, true) as Entity;
                        if (entity != null)
                        { entityCollection.Add(entity); }
                    }
                    trans.Commit();
                }
            }
            return entityCollection;
        }
        //扫描分析
        [CommandMethod("ScanAnalyze")]
        public static void ScanAnalyze()
        {
            // 获得当前文档和数据库   Get the current document and database
            Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Database acCurDb = acDoc.Database;
            Editor acDocEd = acDoc.Editor;

            string[] name = acDoc.Name.Split('.');//获得当前文档的路径名称
            string iniName = name[0] + ".ini";//在当前文档的路径下取得以当前文档命名的ini文件
            if (!File.Exists(@iniName))
            {
                MessageBox.Show("参数配置文件不存在，请先进行参数配置！");
                return;
            }
            string LayerBuild = ReadIniTxt(iniName, "layer", "building_layer");
            string LayerTianxian = ReadIniTxt(iniName, "layer", "antenna_layer");
            string penet0 = ReadIniTxt(iniName, "attenuation", "penetrance_attenuation");//读取上次设置的衰减度
            if (!isNumberic(penet0))
            {
                MessageBox.Show("衰减度值必须为数字，请设置正确的衰减度，如10");
                return;
            }
            double penet0_1 = Convert.ToDouble(penet0);
            string scale = ReadIniTxt(iniName, "scale", "drawing_scale");
            if (!isNumberic(scale))
            {
                MessageBox.Show("比例因子必须为数字，请设置正确的比例因子，如100");
                return;
            }
            double rate = Convert.ToDouble(scale);//比例因子
            //acDocEd.WriteMessage("\n" + LayerBuild);
            //acDocEd.WriteMessage("\n" + LayerTianxian);
            //acDocEd.WriteMessage("\n" + scale);
            //double dAng = 0.0349;
            
            //string IniFileName = System.Windows.Forms.Application.StartupPath + "\\Config\\sys.ini";//存储用户名和密码的文件
            //string IniFile = System.Windows.Forms.Application.StartupPath + "\\Config";
            string IniSysFileName = WlanDesign.FormStartup.IniSysFileName;
            //acDocEd.WriteMessage(IniSysFileName);
            if (!File.Exists(@IniSysFileName))
            {
                MessageBox.Show("系统配置文件不存在，请先下载系统配置文件！");
                return;
            }
            string rays = ReadIniTxt(IniSysFileName, "parameter", "rays");
            if (!isNumberic(rays))
            {
                MessageBox.Show("系统配置文件中射线条数必须为数字，请设置正确的射线条数，如180");
                return;
            }
            int raysNum = Convert.ToInt32(rays);//射线条数
            if (raysNum > 360)
            {
                raysNum = 360;
            }
            double degree = 360 / raysNum;//每两条射线之间的角度
            double dAng = ConvertDegreesToRadians(degree);//阵列中射线偏转弧度
            string cells = ReadIniTxt(IniSysFileName, "parameter", "cells");
            if (!isNumberic(cells))
            {
                MessageBox.Show("系统配置文件中方块数必须为数字，请设置正确的方块数，如10000");
                return;
            }
            double cellsNum = Convert.ToDouble(cells);//覆盖方块数
            int mSqrt = Convert.ToInt32(Math.Sqrt(cellsNum));
            string invisible = ReadIniTxt(IniSysFileName, "parameter", "invisible");
            if (!isNumberic(invisible))
            {
                MessageBox.Show("系统配置文件中不可见区域方块数必须为数字，请设置正确的方块数，如3");
                return;
            }
            int invisibleNum = Convert.ToInt32(invisible);//限定参考方格的距离
            string endAttenuation = ReadIniTxt(IniSysFileName, "parameter", "attenuation");
            if (!isNumberic(endAttenuation))
            {
                MessageBox.Show("系统配置文件中结束场强值必须为数字，请设置正确的结束场强值，如-100");
                return;
            }
            double endFieldStrength = Convert.ToDouble(endAttenuation);//结束场强值
            //acDocEd.WriteMessage("\n" + rays);
            //acDocEd.WriteMessage("\n" + dAng.ToString());
            //acDocEd.WriteMessage("\n" + cells);
            //acDocEd.WriteMessage("\n" + mSqrt.ToString());
            //acDocEd.WriteMessage("\n" + invisible);
            //acDocEd.WriteMessage("\n" + endAttenuation);


            string frequence = "2400";//默认频率
            string fieldStrength = "15";//默认场强
            double transmission = 10;//透射衰减度

            //double endFieldStrength = -115;//场强结束值
            double dx = 0;
            double dy = 0;

            DBObjectCollection acDBObjCollLvls = new DBObjectCollection();//存放所有小边界框
            //DBObjectCollection acDBCircleObjColls = new DBObjectCollection();//存放所有新圆
            //DBObjectCollection acDBLineObjColls = new DBObjectCollection();//存放所有新线段
            // 启动一个事务  Start a transaction
            using (DocumentLock acLckDoc = acDoc.LockDocument())
            {
                using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
                {
                    // 以只读方式打开块表记录   Open the Block table record for read
                    BlockTable acBlkTbl;
                    acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId, OpenMode.ForRead) as BlockTable;
                    // 以写方式打开模型空间块表记录   Open the Block table record Model space for write
                    BlockTableRecord acBlkTblRec;
                    acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;
                    ObjectIdCollection acTianxianObjIdCol = new ObjectIdCollection();
                    foreach (ObjectId asObjId in acBlkTblRec)
                    {
                        Entity acEnt = acTrans.GetObject(asObjId, OpenMode.ForWrite) as Entity;
                        if (LayerTianxian.Contains(acEnt.Layer) && acEnt.GetType().Name == "BlockReference")
                        {
                            BlockReference blkRf = acEnt as BlockReference;
                            string strname = blkRf.Name;
                            if (strname.Contains("天线"))
                            {
                                acTianxianObjIdCol.Add(asObjId);
                            }
                        }
                    }
                    LayerTable acLyrTbl;
                    acLyrTbl = acTrans.GetObject(acCurDb.LayerTableId, OpenMode.ForRead) as LayerTable;
                    //看是否存在需要的三个层，如不存在，则创建它们（LayerFloorboundary层用于存放用户选择楼层的边界,Layerline层用于存放新产生的线段,Layerpoint层用于存放新线段的交点）
                    if (acLyrTbl.Has(LayerFloorboundary) == false)
                    {
                        LayerTableRecord acLyrTblRec = new LayerTableRecord();
                        acLyrTblRec.Name = LayerFloorboundary;
                        acLyrTbl.UpgradeOpen();
                        acLyrTbl.Add(acLyrTblRec);
                        acTrans.AddNewlyCreatedDBObject(acLyrTblRec, true);
                    }
                    if (acLyrTbl.Has(LayerLittleboundary) == false)
                    {
                        LayerTableRecord acLyrTblRec = new LayerTableRecord();
                        acLyrTblRec.Name = LayerLittleboundary;
                        acLyrTbl.UpgradeOpen();
                        acLyrTbl.Add(acLyrTblRec);
                        acTrans.AddNewlyCreatedDBObject(acLyrTblRec, true);
                    }
                    if (acLyrTbl.Has(Layerline) == false)
                    {
                        LayerTableRecord acLyrTblRec = new LayerTableRecord();
                        acLyrTblRec.Name = Layerline;
                        acLyrTbl.UpgradeOpen();
                        acLyrTbl.Add(acLyrTblRec);
                        acTrans.AddNewlyCreatedDBObject(acLyrTblRec, true);
                    }
                    if (acLyrTbl.Has(LayerHatch) == false)
                    {
                        LayerTableRecord acLyrTblRec = new LayerTableRecord();
                        acLyrTblRec.Name = LayerHatch;
                        acLyrTbl.UpgradeOpen();
                        acLyrTbl.Add(acLyrTblRec);
                        acTrans.AddNewlyCreatedDBObject(acLyrTblRec, true);
                    }
                    if (acLyrTbl.Has(LayerCircle) == false)
                    {
                        LayerTableRecord acLyrTblRec = new LayerTableRecord();
                        acLyrTblRec.Name = LayerCircle;
                        acLyrTbl.UpgradeOpen();
                        acLyrTbl.Add(acLyrTblRec);
                        acTrans.AddNewlyCreatedDBObject(acLyrTblRec, true);
                    }
                    if (acLyrTbl.Has(LayerExplode) == false)
                    {
                        LayerTableRecord acLyrTblRec = new LayerTableRecord();
                        acLyrTblRec.Name = LayerExplode;
                        acLyrTbl.UpgradeOpen();
                        acLyrTbl.Add(acLyrTblRec);
                        acTrans.AddNewlyCreatedDBObject(acLyrTblRec, true);
                    }
                    ObjectIdCollection acRayObjIdCol = new ObjectIdCollection();//运算过程中产生的射线集合
                    ObjectIdCollection acObjIdCol = new ObjectIdCollection();//组成指定范围建筑物的对象集合
                    ObjectIdCollection acCirObjIdCol = new ObjectIdCollection();
                    Polyline acPoly = new Polyline();
                    try
                    {
                        PromptEntityResult p = acDocEd.GetEntity("请选择楼层框：");
                        Entity selEnt = acTrans.GetObject(p.ObjectId, OpenMode.ForWrite) as Entity;
                        if (selEnt.GetType().Name != "Polyline" || selEnt.Layer != LayerFloorboundary)
                        {
                            //acDocEd.WriteMessage("请选择正确的楼层框！");
                            MessageBox.Show("请选择正确的楼层框！");
                            return;
                        }
                        acPoly = (Polyline)selEnt;
                    }
                    catch
                    {
                        MessageBox.Show("选择不正确，请重新选择!");
                        return;
                    }
                    acObjIdCol.Add(acPoly.ObjectId);
                    Point2d p0 = acPoly.GetPoint2dAt(0);
                    Point2d p1 = acPoly.GetPoint2dAt(1);
                    Point2d p2 = acPoly.GetPoint2dAt(2);
                    Point3d ptStart = new Point3d(p0.X, p0.Y, 0);
                    Point3d ptEnd = new Point3d(p2.X, p2.Y, 0);
                    //acDocEd.WriteMessage(acDBObjCollLvls.Count.ToString());
                    PromptSelectionResult acSSPrompt;
                    acSSPrompt = acDoc.Editor.SelectWindow(ptStart, ptEnd);
                    int apNum = 0;//天线的数量
                    if (acSSPrompt.Status == PromptStatus.OK)
                    {
                        SelectionSet acSSet = acSSPrompt.Value;
                        foreach (SelectedObject acSSObj in acSSet)
                        {
                            Entity acEnt = acTrans.GetObject(acSSObj.ObjectId, OpenMode.ForWrite) as Entity;
                            if (acEnt.GetType().Name == "Hatch" && acEnt.Layer == LayerHatch)
                            {
                                acEnt.Erase();
                            }
                            if (acEnt.Layer == LayerBuild && (acEnt.GetType().Name == "Line" || acEnt.GetType().Name == "Arc"))
                            {
                                var rb_0 = acEnt.GetXDataForApplication("degreeofdecay");//提取建筑物的衰减度
                                if (rb_0 == null)
                                {
                                    MessageBox.Show("请先进行衰减度设定！");
                                    return;
                                }
                                acObjIdCol.Add(acEnt.ObjectId);
                            }
                        }
                        foreach (SelectedObject acSSObj in acSSet)
                        {
                            // 检查以确定返回的 SelectedObject 对象是有效的     Check to make sure a valid SelectedObject object was returned
                            if (acSSObj != null)
                            {
                                Entity acEnt = acTrans.GetObject(acSSObj.ObjectId, OpenMode.ForWrite) as Entity;
                                if (acEnt.Layer == LayerBuild && (acEnt.GetType().Name == "Polyline"))
                                {
                                    DBObjectCollection acDbPolyObjCol = new DBObjectCollection();
                                    acEnt.Explode(acDbPolyObjCol);
                                    if (acDbPolyObjCol.Count > 0)
                                    {
                                        foreach (Entity acPolyExplode in acDbPolyObjCol)
                                        {
                                            if (acPolyExplode.GetType().Name == "Line" || acPolyExplode.GetType().Name == "Arc")
                                            {
                                                acPolyExplode.Layer = LayerExplode;
                                                var rb = acPolyExplode.GetXDataForApplication("degreeofdecay");
                                                if (rb == null)
                                                {
                                                    var rat = acTrans.GetObject(acCurDb.RegAppTableId, OpenMode.ForWrite) as RegAppTable;
                                                    if (!rat.Has("degreeofdecay"))
                                                    {
                                                        var ratr = new RegAppTableRecord();
                                                        ratr.Name = "degreeofdecay";
                                                        rat.Add(ratr);
                                                        acTrans.AddNewlyCreatedDBObject(ratr, true);
                                                    }
                                                    ResultBuffer resb = new ResultBuffer(new TypedValue(1001, "degreeofdecay"), new TypedValue(1000, penet0_1));
                                                    acPolyExplode.XData = resb;
                                                    resb.Dispose();
                                                }
                                                acBlkTblRec.AppendEntity(acPolyExplode);
                                                acTrans.AddNewlyCreatedDBObject(acPolyExplode, true);
                                                acObjIdCol.Add(acPolyExplode.ObjectId);
                                            }
                                        }
                                    }
                                }
                                if (LayerTianxian.Contains(acEnt.Layer) && acEnt.GetType().Name == "BlockReference")
                                {
                                    BlockReference blkRf = acEnt as BlockReference;
                                    string strname = blkRf.Name;
                                    if (strname.Contains("天线"))
                                    {
                                        bool isHaveFieldStrength = false;
                                        AttributeCollection attCol = blkRf.AttributeCollection;
                                        foreach (ObjectId attId in attCol)
                                        {
                                            AttributeReference attRef = (AttributeReference)acTrans.GetObject(attId, OpenMode.ForRead);
                                            string str = attRef.Tag;
                                            if (str.Contains("NUM"))
                                            {
                                                string strValue = attRef.TextString;
                                                bool tianXian = false;
                                                foreach (ObjectId acTianxianObjId in acTianxianObjIdCol)
                                                {
                                                    BlockReference acBlkTianxian = acTrans.GetObject(acTianxianObjId, OpenMode.ForWrite) as BlockReference;
                                                    AttributeCollection attTianxianCol = acBlkTianxian.AttributeCollection;
                                                    foreach (ObjectId attTianxianId in attTianxianCol)
                                                    {
                                                        AttributeReference attTianxianRef = (AttributeReference)acTrans.GetObject(attTianxianId, OpenMode.ForRead);
                                                        string str1 = attTianxianRef.Tag;
                                                        if (str1.Contains("NUM"))
                                                        {
                                                            string strValue1 = attTianxianRef.TextString;
                                                            if (strValue == strValue1)
                                                            {
                                                                double maxFieldStrength = -100;
                                                                foreach (ObjectId attTianxianId_1 in attTianxianCol)
                                                                {
                                                                    AttributeReference attTianxianRef_1 = (AttributeReference)acTrans.GetObject(attTianxianId_1, OpenMode.ForRead);
                                                                    string str1_1 = attTianxianRef_1.Tag;
                                                                    if (str1_1.Contains("OUT"))
                                                                    {
                                                                        string strValue1_1 = attTianxianRef_1.TextString;
                                                                        if (strValue1_1 != "")
                                                                        {
                                                                            strValue1_1 = strValue1_1.Substring(1);
                                                                            if (isNumberic(strValue1_1))
                                                                            {
                                                                                double strFieldStrength = Convert.ToDouble(strValue1_1);
                                                                                if (strFieldStrength >= maxFieldStrength)
                                                                                {
                                                                                    maxFieldStrength = strFieldStrength;
                                                                                    fieldStrength = strValue1_1;
                                                                                }
                                                                            }
                                                                        }
                                                                    }
                                                                }
                                                                if (maxFieldStrength > -100)
                                                                {
                                                                    tianXian = true;
                                                                    isHaveFieldStrength = true;
                                                                }
                                                            }
                                                        }
                                                        if (tianXian == true)
                                                        {
                                                            break;
                                                        }
                                                    }
                                                    if (tianXian == true)
                                                    {
                                                        break;
                                                    }
                                                }
                                            }
                                        }
                                        if (isHaveFieldStrength == false)
                                        {
                                            if (acRayObjIdCol.Count > 0)
                                            {
                                                foreach (ObjectId asRayObjId in acRayObjIdCol)
                                                {
                                                    Entity acEntRay = acTrans.GetObject(asRayObjId, OpenMode.ForWrite) as Entity;
                                                    acEntRay.Erase();
                                                }
                                            }
                                            if (acCirObjIdCol.Count > 0)
                                            {
                                                foreach (ObjectId asCirObjId in acCirObjIdCol)
                                                {
                                                    Entity acEntCir = acTrans.GetObject(asCirObjId, OpenMode.ForWrite) as Entity;
                                                    acEntCir.Erase();
                                                }
                                            }
                                            MessageBox.Show("所选区域中有不合法的天线，请修正！");
                                            return;
                                        }
                                        apNum++;
                                        string apNum_1 = Convert.ToString(apNum);
                                        int nCount = 1;
                                        Ray acRay = new Ray();
                                        acRay.BasePoint = blkRf.Position;
                                        acRay.SecondPoint = new Point3d(blkRf.Position.X + 1, blkRf.Position.Y + 1, 0);
                                        for (int i = 0; i < 5; i++)
                                        {
                                            Circle acCir = new Circle();
                                            acCir.Center = blkRf.Position;
                                            acCir.Radius = (Math.Pow(2, (i * 1.0))) * 1.0 * rate;
                                            acCir.Layer = LayerCircle;
                                            acBlkTblRec.AppendEntity(acCir);
                                            acTrans.AddNewlyCreatedDBObject(acCir, true);
                                            acObjIdCol.Add(acCir.ObjectId);
                                            acCirObjIdCol.Add(acCir.ObjectId);
                                            //acDBCircleObjColls.Add(acCir);
                                            var rb = acCir.GetXDataForApplication("ApNum");
                                            if (rb == null)
                                            {
                                                var rat = acTrans.GetObject(acCurDb.RegAppTableId, OpenMode.ForWrite) as RegAppTable;
                                                if (!rat.Has("ApNum"))
                                                {
                                                    var ratr = new RegAppTableRecord();
                                                    ratr.Name = "ApNum";
                                                    rat.Add(ratr);
                                                    acTrans.AddNewlyCreatedDBObject(ratr, true);
                                                }
                                                ResultBuffer resb = new ResultBuffer(new TypedValue(1001, "ApNum"), new TypedValue(1000, apNum_1));
                                                acCir.XData = resb;
                                                resb.Dispose();
                                            }
                                        }
                                        Point2d acPt2dArrayBase = new Point2d(blkRf.Position.X, blkRf.Position.Y);
                                        Point3d acPt3dArrayBase = blkRf.Position;
                                        Matrix3d curUCSMatrix = acDoc.Editor.CurrentUserCoordinateSystem;
                                        CoordinateSystem3d curUCS = curUCSMatrix.CoordinateSystem3d;
                                        while (nCount <= raysNum)
                                        {
                                            /*
                                            Point2d acPtObjBase = new Point2d(acRay.SecondPoint.X, acRay.SecondPoint.Y);
                                            Ray acRay_1 = new Ray();
                                            double dDist = acPt2dArrayBase.GetDistanceTo(acPtObjBase);
                                            double dAngFromX = acPt2dArrayBase.GetVectorTo(acPtObjBase).Angle;
                                            Point2d acPt2dTo = PolarPoints(acPt2dArrayBase, (nCount * dAng) + dAngFromX, dDist);
                                            Point3d acPt3dTo = new Point3d(acPt2dTo.X, acPt2dTo.Y, 0);
                                            acRay_1.BasePoint = acPt3dArrayBase;
                                            acRay_1.SecondPoint = acPt3dTo;
                                            acRay_1.ColorIndex = 1;
                                            acBlkTblRec.AppendEntity(acRay_1);
                                            acTrans.AddNewlyCreatedDBObject(acRay_1, true);
                                             */
                                            Ray acRay_1 = (Ray)acRay.Clone();
                                            acRay_1.TransformBy(Matrix3d.Rotation(nCount * dAng, curUCS.Zaxis, acPt3dArrayBase));
                                            acBlkTblRec.AppendEntity(acRay_1);
                                            acTrans.AddNewlyCreatedDBObject(acRay_1, true);
                                            var rb = acRay_1.GetXDataForApplication("Parameters");
                                            if (rb == null)
                                            {
                                                var rat = acTrans.GetObject(acCurDb.RegAppTableId, OpenMode.ForWrite) as RegAppTable;
                                                if (!rat.Has("Parameters"))
                                                {
                                                    var ratr = new RegAppTableRecord();
                                                    ratr.Name = "Parameters";
                                                    rat.Add(ratr);
                                                    acTrans.AddNewlyCreatedDBObject(ratr, true);
                                                }
                                                ResultBuffer resb = new ResultBuffer(new TypedValue(1001, "Parameters"), new TypedValue(1000, fieldStrength), new TypedValue(1000, frequence), new TypedValue(1000, "0"), new TypedValue(1000, apNum_1));
                                                //ResultBuffer resb = new ResultBuffer(new TypedValue(1001, "Parameters"), new TypedValue(1000, fieldStrength), new TypedValue(1000, frequence), new TypedValue(1000, "0"), new TypedValue(1000, "0"));
                                                acRay_1.XData = resb;
                                                resb.Dispose();
                                            }
                                            nCount = nCount + 1;
                                            acRayObjIdCol.Add(acRay_1.ObjectId);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    if (acRayObjIdCol.Count == 0)
                    {
                        MessageBox.Show("此区域没有天线！");
                        return;
                    }
                    //在指定区域内创建m*n的边界框矩形阵列
                    int m = mSqrt;
                    int n = mSqrt;
                    // 设置行和列的偏移距离和阵列角度
                    dx = (p2.X - p0.X) / m;
                    dy = (p0.Y - p2.Y) / n;
                    double dPolyArrayAng = 0;
                    Point2d p00 = new Point2d(p1.X, p1.Y);
                    Point2d p11 = new Point2d(p1.X + dx, p1.Y);
                    Point2d p22 = new Point2d(p1.X + dx, p1.Y + dy);
                    Point2d p33 = new Point2d(p1.X, p1.Y + dy);
                    Polyline acPoly_1 = new Polyline();
                    acPoly_1.SetDatabaseDefaults();
                    acPoly_1.AddVertexAt(0, p00, 0, 0, 0);
                    acPoly_1.AddVertexAt(1, p11, 0, 0, 0);
                    acPoly_1.AddVertexAt(2, p22, 0, 0, 0);
                    acPoly_1.AddVertexAt(3, p33, 0, 0, 0);
                    acPoly_1.AddVertexAt(4, p00, 0, 0, 0);
                    acPoly_1.Closed = true;
                    acPoly_1.Layer = LayerLittleboundary;
                    acBlkTblRec.AppendEntity(acPoly_1);
                    acTrans.AddNewlyCreatedDBObject(acPoly_1, true);
                    // Get the angle from X for the current UCS 
                    Matrix3d curPolyUCSMatrix = acDocEd.CurrentUserCoordinateSystem;
                    CoordinateSystem3d curPolyUCS = curPolyUCSMatrix.CoordinateSystem3d;
                    Vector2d acPolyVec2dAng = new Vector2d(curPolyUCS.Xaxis.X, curPolyUCS.Xaxis.Y);
                    // If the UCS is rotated, adjust the array angle accordingly
                    dPolyArrayAng = dPolyArrayAng + acPolyVec2dAng.Angle;
                    // Use the upper-left corner of the objects extents for the array base point
                    Extents3d acPolyExts = acPoly_1.Bounds.GetValueOrDefault();
                    Point2d acPt2PolydArrayBase = new Point2d(acPolyExts.MinPoint.X, acPolyExts.MaxPoint.Y);
                    // Track the objects created for each column
                    DBObjectCollection acDBObjCollCols = new DBObjectCollection();
                    acDBObjCollCols.Add(acPoly_1);
                    int nColumnsCount = 1;
                    while (n > nColumnsCount)
                    {
                        Entity acEntClone = acPoly_1.Clone() as Entity;
                        acDBObjCollCols.Add(acEntClone);
                        // Caclucate the new point for the copied object (move)
                        Point2d acPt2dTo = PolarPoints(acPt2PolydArrayBase, dPolyArrayAng, dx * nColumnsCount);
                        Vector2d acVec2d = acPt2PolydArrayBase.GetVectorTo(acPt2dTo);
                        Vector3d acVec3d = new Vector3d(acVec2d.X, acVec2d.Y, 0);
                        acEntClone.TransformBy(Matrix3d.Displacement(acVec3d));
                        acBlkTblRec.AppendEntity(acEntClone);
                        acTrans.AddNewlyCreatedDBObject(acEntClone, true);
                        nColumnsCount = nColumnsCount + 1;
                    }
                    // Set a value in radians for 90 degrees
                    double dPolyAng = Math.PI / 2;
                    // Track the objects created for each row and column

                    foreach (DBObject acObj in acDBObjCollCols)
                    {
                        acDBObjCollLvls.Add(acObj);
                    }
                    // Create the number of objects for each row
                    foreach (Entity acEnt in acDBObjCollCols)
                    {
                        int nRowsCount = 1;
                        while (m > nRowsCount)
                        {
                            Entity acEntClone = acEnt.Clone() as Entity;
                            acDBObjCollLvls.Add(acEntClone);
                            // Caclucate the new point for the copied object (move)
                            Point2d acPt2dTo = PolarPoints(acPt2PolydArrayBase, dPolyArrayAng + dPolyAng, dy * nRowsCount);
                            Vector2d acVec2d = acPt2PolydArrayBase.GetVectorTo(acPt2dTo);
                            Vector3d acVec3d = new Vector3d(acVec2d.X, acVec2d.Y, 0);
                            acEntClone.TransformBy(Matrix3d.Displacement(acVec3d));
                            acBlkTblRec.AppendEntity(acEntClone);
                            acTrans.AddNewlyCreatedDBObject(acEntClone, true);
                            nRowsCount = nRowsCount + 1;
                        }
                    }
                    ProgressMeter pm_1 = new ProgressMeter();
                    pm_1.Start("正在进行射线跟踪分析，请耐心等待！");
                    pm_1.SetLimit(100);
                    int pmstr;
                    pmstr = (int)acRayObjIdCol.Count / 100 + 1;
                    //遍历射线集合，进行相应处理
                    for (int i = 0; i < acRayObjIdCol.Count; i++)
                    {
                        ObjectId acRayObjId = acRayObjIdCol[i];
                        if (i % pmstr == 0)
                        {
                            System.Threading.Thread.Sleep(5);
                            pm_1.MeterProgress();
                            System.Windows.Forms.Application.DoEvents();
                        }
                        Ray acRay_1 = acTrans.GetObject(acRayObjId, OpenMode.ForWrite, false) as Ray;
                        DBObjectCollection acDyObjIdCol = new DBObjectCollection();//保存与主射线只有一个交点的建筑
                        ObjectIdCollection acDyRayObjIdCol = new ObjectIdCollection();//保存主射线和产生的子射线
                        acDyRayObjIdCol.Add(acRayObjId);
                        foreach (ObjectId acObjId in acObjIdCol)
                        {
                            Entity ent = acTrans.GetObject(acObjId, OpenMode.ForWrite, false) as Entity;
                            if (ent.GetType().Name == "Arc" || ent.GetType().Name == "Line" || ent.GetType().Name == "Polyline" || ent.GetType().Name == "Circle")
                            {
                                Curve acCur = (Curve)ent;
                                Point3dCollection points = new Point3dCollection();
                                acRay_1.IntersectWith(acCur, Intersect.OnBothOperands, points, 0, 0);
                                if (points.Count == 1 && points[0] != acRay_1.BasePoint)
                                {
                                    acDyObjIdCol.Add(ent);
                                }
                            }
                        }
                        foreach (ObjectId acDyRayObjId in acDyRayObjIdCol)
                        {
                            Ray acRay_1_1 = acTrans.GetObject(acDyRayObjId, OpenMode.ForWrite, false) as Ray;
                            var rb = acRay_1_1.GetXDataForApplication("Parameters");//提取射线中的参数，查看其场强和频率
                            if (rb != null)
                            {
                                List<TypedValue> values = rb.Cast<TypedValue>().ToList();
                                double value = Convert.ToDouble(values[1].Value);//读取该条射线的场强，并把其转换为整型
                                string value_1 = Convert.ToString(value);//将整型转换为字符串型
                                double value2 = Convert.ToDouble(values[2].Value);//读取该条射线的频率
                                string value_2 = Convert.ToString(value2);
                                double value3 = Convert.ToDouble(values[3].Value);//读取该条射线已经过的路径长度
                                string value_3 = Convert.ToString(value3);
                                int value4 = Convert.ToInt32(values[4].Value);//读取该条射线所对应的Ap天线的Id
                                string value_4 = Convert.ToString(value4);
                                Line acLine = new Line();//创建新线段，用于保存射线起点到遇到障碍物之间的线段
                                DBObjectCollection acRayIntersectObjIdCol = new DBObjectCollection();//创建ObjectId集合，用于保存与该条射线有一个交点的建筑物，便于求取与该射线第一次相交的建筑
                                double length = 1000 * rate;//定义初始与该射线起点最近的建筑物的距离
                                //如果该射线的场强大于0
                                if (value > endFieldStrength)
                                //if (value > endFieldStrength && value4 <= nMax)
                                {
                                    //遍历建筑，得到射线起点到遇到的第一个障碍物之间的线段
                                    foreach (Entity acObjId in acDyObjIdCol)
                                    {
                                        Entity ent = (Entity)acObjId;
                                        if (ent.GetType().Name == "Arc" || ent.GetType().Name == "Line" || ent.GetType().Name == "Polyline")
                                        {
                                            Curve acCur = (Curve)ent;
                                            Point3dCollection points = new Point3dCollection();
                                            acRay_1_1.IntersectWith(acCur, Intersect.OnBothOperands, points, 0, 0);
                                            if (points.Count == 1 && points[0] != acRay_1_1.BasePoint)
                                            {

                                                Line acLine_1 = new Line(acRay_1_1.BasePoint, points[0]);
                                                if (acLine_1.Length < length)
                                                {
                                                    acRayIntersectObjIdCol.Add(ent);
                                                    length = acLine_1.Length;
                                                    acLine = acLine_1;
                                                }
                                            }
                                        }
                                        else if (ent.GetType().Name == "Circle" && ent.Layer == LayerCircle)
                                        {
                                            var rb_0 = ent.GetXDataForApplication("ApNum");//
                                            if (rb_0 != null)
                                            {
                                                List<TypedValue> values_0 = rb_0.Cast<TypedValue>().ToList();
                                                string value_0 = Convert.ToString(values_0[1].Value);//
                                                if (value_0 == value_4)
                                                {
                                                    Circle acCirle = (Circle)ent;
                                                    Point3dCollection points = new Point3dCollection();
                                                    acRay_1_1.IntersectWith(acCirle, Intersect.OnBothOperands, points, 0, 0);
                                                    if (points.Count == 1 && points[0] != acRay_1_1.BasePoint)
                                                    {
                                                        Line acLine_1 = new Line(acRay_1_1.BasePoint, points[0]);
                                                        if (acLine_1.Length < length)
                                                        {
                                                            acRayIntersectObjIdCol.Add(ent);
                                                            length = acLine_1.Length;
                                                            acLine = acLine_1;
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    //遍历与射线有交点的建筑
                                    foreach (Entity acRayIntersectObjId in acRayIntersectObjIdCol)
                                    {
                                        Curve ent = (Curve)acRayIntersectObjId;
                                        Point3dCollection points = new Point3dCollection();
                                        acLine.IntersectWith(ent, Intersect.OnBothOperands, points, 0, 0);
                                        //如果该建筑与射线的交点为新线段的终点，则此建筑为射线遇到的第一个建筑
                                        if (points.Count == 1 && points[0] != acRay_1_1.BasePoint)
                                        {
                                            //如果该建筑是我们框选的边框
                                            if (ent == acPoly)
                                            {
                                                var rb_1 = acLine.GetXDataForApplication("Parameters");
                                                if (rb_1 == null)
                                                {
                                                    var rat_1 = acTrans.GetObject(acCurDb.RegAppTableId, OpenMode.ForWrite) as RegAppTable;
                                                    if (!rat_1.Has("Parameters"))
                                                    {
                                                        var ratr_1 = new RegAppTableRecord();
                                                        ratr_1.Name = "Parameters";
                                                        rat_1.Add(ratr_1);
                                                        acTrans.AddNewlyCreatedDBObject(ratr_1, true);
                                                    }
                                                    ResultBuffer resb_1 = new ResultBuffer(new TypedValue(1001, "Parameters"), new TypedValue(1000, value_1), new TypedValue(1000, value_2));
                                                    acLine.XData = resb_1;
                                                    resb_1.Dispose();
                                                }
                                                //将新线段添加到模型空间
                                                acLine.Layer = Layerline;
                                                acBlkTblRec.AppendEntity(acLine);
                                                acTrans.AddNewlyCreatedDBObject(acLine, true);
                                                //acDBLineObjColls.Add(acLine);//将产生的线段加入线段集合
                                            }
                                            else if (ent.GetType().Name == "Circle" && ent.Layer == LayerCircle)
                                            {
                                                var rb_1 = acLine.GetXDataForApplication("Parameters");
                                                if (rb_1 == null)
                                                {
                                                    var rat_1 = acTrans.GetObject(acCurDb.RegAppTableId, OpenMode.ForWrite) as RegAppTable;
                                                    if (!rat_1.Has("Parameters"))
                                                    {
                                                        var ratr_1 = new RegAppTableRecord();
                                                        ratr_1.Name = "Parameters";
                                                        rat_1.Add(ratr_1);
                                                        acTrans.AddNewlyCreatedDBObject(ratr_1, true);
                                                    }
                                                    ResultBuffer resb_1 = new ResultBuffer(new TypedValue(1001, "Parameters"), new TypedValue(1000, value_1), new TypedValue(1000, value_2));
                                                    acLine.XData = resb_1;
                                                    resb_1.Dispose();
                                                }
                                                //将新线段添加到模型空间
                                                acLine.Layer = Layerline;
                                                acBlkTblRec.AppendEntity(acLine);
                                                acTrans.AddNewlyCreatedDBObject(acLine, true);
                                                //acDBLineObjColls.Add(acLine);//将产生的线段加入线段集合
                                                Ray acRay_2 = new Ray();
                                                acRay_2.BasePoint = acLine.EndPoint;
                                                //Vector3d a = new Vector3d(acLine.EndPoint.X - acLine.StartPoint.X, acLine.EndPoint.Y - acLine.StartPoint.Y, acLine.EndPoint.Z - acLine.StartPoint.Z);//透射线的方向，与原射线方向一致
                                                acRay_2.UnitDir = acRay_1_1.UnitDir;//透射线的单位向量
                                                //给透射线赋值（场强、频率和已经过的路径长度及Id）
                                                var rb_2 = acRay_2.GetXDataForApplication("Parameters");
                                                if (rb_2 == null)
                                                {
                                                    var rat_2 = acTrans.GetObject(acCurDb.RegAppTableId, OpenMode.ForWrite) as RegAppTable;
                                                    if (!rat_2.Has("Parameters"))
                                                    {
                                                        var ratr_2 = new RegAppTableRecord();
                                                        ratr_2.Name = "Parameters";
                                                        rat_2.Add(ratr_2);
                                                        acTrans.AddNewlyCreatedDBObject(ratr_2, true);
                                                    }
                                                    double attenuation = 0;
                                                    if (value3 != 0)
                                                    {
                                                        attenuation = GetDistanceAttenuation(value2, ((acLine.Length + value3) / rate) / 1000) - GetDistanceAttenuation(value2, (value3 / rate) / 1000);
                                                    }
                                                    else
                                                    {
                                                        attenuation = GetDistanceAttenuation(value2, (acLine.Length / rate) / 1000);
                                                    }
                                                    value = value - attenuation;
                                                    value_1 = Convert.ToString(value);
                                                    value3 = value3 + acLine.Length;
                                                    value_3 = Convert.ToString(value3);
                                                    ResultBuffer resb_2 = new ResultBuffer(new TypedValue(1001, "Parameters"), new TypedValue(1000, value_1), new TypedValue(1000, value_2), new TypedValue(1000, value_3), new TypedValue(1000, value_4));
                                                    acRay_2.XData = resb_2;
                                                    resb_2.Dispose();
                                                }
                                                acBlkTblRec.AppendEntity(acRay_2);
                                                acTrans.AddNewlyCreatedDBObject(acRay_2, true);
                                                acDyRayObjIdCol.Add(acRay_2.ObjectId);//将新产生的透射线加入到射线集合
                                            }
                                            else
                                            {
                                                var rb_0 = ent.GetXDataForApplication("degreeofdecay");//提取建筑物的衰减度
                                                if (rb_0 != null)
                                                {
                                                    List<TypedValue> values_0 = rb_0.Cast<TypedValue>().ToList();
                                                    if (isNumberic(Convert.ToString(values_0[1].Value)))
                                                    {
                                                        double value_0 = Convert.ToDouble(values_0[1].Value);//读取该建筑的透射衰减度
                                                        transmission = value_0;
                                                    }
                                                }
                                                //给新线段赋参数（场强和频率）
                                                var rb_1 = acLine.GetXDataForApplication("Parameters");
                                                if (rb_1 == null)
                                                {
                                                    var rat_1 = acTrans.GetObject(acCurDb.RegAppTableId, OpenMode.ForWrite) as RegAppTable;
                                                    if (!rat_1.Has("Parameters"))
                                                    {
                                                        var ratr_1 = new RegAppTableRecord();
                                                        ratr_1.Name = "Parameters";
                                                        rat_1.Add(ratr_1);
                                                        acTrans.AddNewlyCreatedDBObject(ratr_1, true);
                                                    }
                                                    ResultBuffer resb_1 = new ResultBuffer(new TypedValue(1001, "Parameters"), new TypedValue(1000, value_1), new TypedValue(1000, value_2));
                                                    acLine.XData = resb_1;
                                                    resb_1.Dispose();
                                                }
                                                //acLine.Color = acRay_1.Color;
                                                //将新线段添加到模型空间
                                                acLine.Layer = Layerline;
                                                acBlkTblRec.AppendEntity(acLine);
                                                acTrans.AddNewlyCreatedDBObject(acLine, true);
                                                //acDBLineObjColls.Add(acLine);//将产生的线段加入线段集合
                                                //Point3d acAntipolePoint = GetAntipolePoint(acRay_1.BasePoint, acLine.EndPoint);
                                                //创建透射线
                                                Ray acRay_2 = new Ray();
                                                acRay_2.BasePoint = acLine.EndPoint;
                                                //Vector3d a = new Vector3d(acLine.EndPoint.X - acLine.StartPoint.X, acLine.EndPoint.Y - acLine.StartPoint.Y, acLine.EndPoint.Z - acLine.StartPoint.Z);//透射线的方向，与原射线方向一致
                                                acRay_2.UnitDir = acRay_1_1.UnitDir;//透射线的单位向量
                                                //acRay_2.SecondPoint = acAntipolePoint;
                                                //acRay_2.ColorIndex = 4;//透射线的颜色
                                                //给透射线赋值（场强、频率和已经过的路径长度及迭代次数）
                                                var rb_2 = acRay_2.GetXDataForApplication("Parameters");
                                                if (rb_2 == null)
                                                {
                                                    var rat_2 = acTrans.GetObject(acCurDb.RegAppTableId, OpenMode.ForWrite) as RegAppTable;
                                                    if (!rat_2.Has("Parameters"))
                                                    {
                                                        var ratr_2 = new RegAppTableRecord();
                                                        ratr_2.Name = "Parameters";
                                                        rat_2.Add(ratr_2);
                                                        acTrans.AddNewlyCreatedDBObject(ratr_2, true);
                                                    }
                                                    double attenuation = 0;
                                                    if (value3 != 0)
                                                    {
                                                        attenuation = GetDistanceAttenuation(value2, ((acLine.Length + value3) / rate) / 1000) - GetDistanceAttenuation(value2, (value3 / rate) / 1000);
                                                    }
                                                    else
                                                    {
                                                        attenuation = GetDistanceAttenuation(value2, (acLine.Length / rate) / 1000);
                                                    }
                                                    value = value - transmission - attenuation;
                                                    value_1 = Convert.ToString(value);
                                                    value3 = value3 + acLine.Length;
                                                    value_3 = Convert.ToString(value3);
                                                    //value4 = value4 + 1;
                                                    //value_4 = Convert.ToString(value4);
                                                    ResultBuffer resb_2 = new ResultBuffer(new TypedValue(1001, "Parameters"), new TypedValue(1000, value_1), new TypedValue(1000, value_2), new TypedValue(1000, value_3), new TypedValue(1000, value_4));
                                                    acRay_2.XData = resb_2;
                                                    resb_2.Dispose();
                                                }
                                                acBlkTblRec.AppendEntity(acRay_2);
                                                acTrans.AddNewlyCreatedDBObject(acRay_2, true);
                                                acDyRayObjIdCol.Add(acRay_2.ObjectId);//将新产生的透射线加入到射线集合
                                            }
                                            break;
                                        }
                                    }
                                }
                            }
                            acRay_1_1.Erase();
                        }
                    }
                    pm_1.Stop();
                    acTrans.Commit();
                }
                using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
                {
                    // 以只读方式打开块表记录   Open the Block table record for read
                    BlockTable acBlkTbl;
                    acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId, OpenMode.ForWrite) as BlockTable;
                    // 以写方式打开模型空间块表记录   Open the Block table record Model space for write
                    BlockTableRecord acBlkTblRec;
                    acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;
                    ObjectIdCollection acHatchObjIdCol = new ObjectIdCollection();//组成指定范围填充器对象ObjectId集合
                    ObjectIdCollection acLittleBoundaryObjIdCol = new ObjectIdCollection();
                    foreach (ObjectId asObjId in acBlkTblRec)
                    {
                        Entity ent = acTrans.GetObject(asObjId, OpenMode.ForWrite, false) as Entity;
                        if (ent.Layer == LayerLittleboundary&&ent.GetType().Name=="Polyline")
                        {
                            acLittleBoundaryObjIdCol.Add(asObjId);
                        }
                    }
                    DrawOrderTable dot = (DrawOrderTable)acTrans.GetObject(acBlkTblRec.DrawOrderTableId, OpenMode.ForWrite);
                    ProgressMeter pm = new ProgressMeter();
                    pm.Start("正在进行覆盖分析，请稍后！");
                    pm.SetLimit(100);
                    int pmstart;
                    pmstart = (int)acLittleBoundaryObjIdCol.Count / 100 + 1;
                    for (int i = 0; i < acLittleBoundaryObjIdCol.Count; i++)
                    {
                        if (i % pmstart == 0)
                        {
                            System.Threading.Thread.Sleep(5);
                            pm.MeterProgress();
                            System.Windows.Forms.Application.DoEvents();
                        }
                        Entity ent = acTrans.GetObject(acLittleBoundaryObjIdCol[i], OpenMode.ForWrite, false) as Entity;
                        Polyline acPolyline = (Polyline)ent;
                        Point3d pPolyLine_1 = acPolyline.GetPoint3dAt(3);
                        Point3d pPolyLine_2 = acPolyline.GetPoint3dAt(1);
                        PromptSelectionResult acPolyLineSSPrompt;
                        acPolyLineSSPrompt = acDocEd.SelectCrossingWindow(pPolyLine_1, pPolyLine_2);
                        // 如果提示状态是 OK，对象就被选择了    If the prompt status is OK, objects were selected
                        if (acPolyLineSSPrompt.Status == PromptStatus.OK)
                        {
                            SelectionSet acSSet = acPolyLineSSPrompt.Value;
                            //Application.ShowAlertDialog("Number of objects selected: " + acSSet.Count.ToString());
                            double acHatchValue1 = -1000;
                            double acHatchValue2 = -1000;
                            if (acSSet.Count > 1)
                            {
                                foreach (SelectedObject acSSObj in acSSet)
                                {
                                    // 检查以确定返回的 SelectedObject 对象是有效的     Check to make sure a valid SelectedObject object was returned
                                    if (acSSObj != null)
                                    {
                                        // 以写的方式打开选择的对象   Open the selected object for write
                                        Entity acPolyLineEnt = acTrans.GetObject(acSSObj.ObjectId, OpenMode.ForWrite) as Entity;
                                        if (acPolyLineEnt != null && acPolyLineEnt.Layer == Layerline)
                                        {
                                            Line acNewLine = (Line)acPolyLineEnt;
                                            var rb = acNewLine.GetXDataForApplication("Parameters");//提取射线中的参数，查看其场强和频率
                                            if (rb != null)
                                            {
                                                List<TypedValue> values = rb.Cast<TypedValue>().ToList();
                                                double value = Convert.ToDouble(values[1].Value);//读取该条射线的场强，并把其转换为整型
                                                double value2 = Convert.ToDouble(values[2].Value);//读取该条射线的频率
                                                if (value > acHatchValue1)
                                                {
                                                    acHatchValue1 = value;
                                                    acHatchValue2 = value2;
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            if (acHatchValue1 == -1000)
                            {
                                bool bol = true;
                                double px1 = pPolyLine_1.X;
                                double py1 = pPolyLine_1.Y;
                                double px2 = pPolyLine_2.X;
                                double py2 = pPolyLine_2.Y;
                                int invisibleNum_1 = 0;
                                while (bol)
                                {
                                    invisibleNum_1++;
                                    if (invisibleNum_1 > invisibleNum)
                                    {
                                        break;
                                    }
                                    px1 = px1 - dx;
                                    py1 = py1 + dy;
                                    px2 = px2 + dx;
                                    py2 = py2 - dy;
                                    Point3d pExtra_1 = new Point3d(px1, py1, 0);
                                    Point3d pExtra_2 = new Point3d(px2, py2, 0);
                                    PromptSelectionResult acPolyLineSSPrompt_1;
                                    acPolyLineSSPrompt_1 = acDocEd.SelectCrossingWindow(pExtra_1, pExtra_2);
                                    if (acPolyLineSSPrompt_1.Status == PromptStatus.OK)
                                    {
                                        SelectionSet acSSet_1 = acPolyLineSSPrompt_1.Value;
                                        if (acSSet_1.Count > 0)
                                        {
                                            foreach (SelectedObject acSSObj_1 in acSSet_1)
                                            {
                                                // 检查以确定返回的 SelectedObject 对象是有效的     Check to make sure a valid SelectedObject object was returned
                                                if (acSSObj_1 != null)
                                                {
                                                    // 以写的方式打开选择的对象   Open the selected object for write
                                                    Entity acPolyLineEnt = acTrans.GetObject(acSSObj_1.ObjectId, OpenMode.ForWrite) as Entity;
                                                    if (acPolyLineEnt != null && acPolyLineEnt.Layer == Layerline)
                                                    {
                                                        Line acNewLine = (Line)acPolyLineEnt;
                                                        var rb = acNewLine.GetXDataForApplication("Parameters");//提取射线中的参数，查看其场强和频率
                                                        if (rb != null)
                                                        {
                                                            List<TypedValue> values = rb.Cast<TypedValue>().ToList();
                                                            double value = Convert.ToDouble(values[1].Value);//读取该条射线的场强
                                                            double value2 = Convert.ToDouble(values[2].Value);//读取该条射线的频率
                                                            if (value > acHatchValue1)
                                                            {
                                                                acHatchValue1 = value;
                                                                acHatchValue2 = value2;
                                                                //acDocEd.WriteMessage(acHatchValue1.ToString());
                                                            }
                                                        }
                                                        bol = false;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            if (acHatchValue1 == -1000)
                            {
                                acPolyline.Erase();
                                continue;
                            }
                            ObjectIdCollection acPolyLineObjIdColl = new ObjectIdCollection();
                            acPolyLineObjIdColl.Add(acPolyline.ObjectId);
                            Hatch acHatch = new Hatch();
                            acHatch.Layer = LayerHatch;
                            acHatch.SetDatabaseDefaults();
                            acHatch.SetHatchPattern(HatchPatternType.PreDefined, "SOLID");
                            var rbHatch = acHatch.GetXDataForApplication("Parameters");
                            if (rbHatch == null)
                            {
                                var rat_3 = acTrans.GetObject(acCurDb.RegAppTableId, OpenMode.ForWrite) as RegAppTable;
                                if (!rat_3.Has("Parameters"))
                                {
                                    var ratr_3 = new RegAppTableRecord();
                                    ratr_3.Name = "Parameters";
                                    rat_3.Add(ratr_3);
                                    acTrans.AddNewlyCreatedDBObject(ratr_3, true);
                                }
                                if (acHatchValue1 > 5)
                                {
                                    acHatch.ColorIndex = 10;
                                }
                                else if (acHatchValue1 > -5 && acHatchValue1 <= 5)
                                {
                                    acHatch.ColorIndex = 20;
                                }
                                else if (acHatchValue1 > -15 && acHatchValue1 <= -5)
                                {
                                    acHatch.ColorIndex = 30;
                                }
                                else if (acHatchValue1 > -25 && acHatchValue1 <= -15)
                                {
                                    acHatch.ColorIndex = 40;
                                }
                                else if (acHatchValue1 > -35 && acHatchValue1 <= -25)
                                {
                                    acHatch.ColorIndex = 50;
                                }
                                else if (acHatchValue1 > -45 && acHatchValue1 <= -35)
                                {
                                    acHatch.ColorIndex = 60;
                                }
                                else if (acHatchValue1 > -55 && acHatchValue1 <= -45)
                                {
                                    acHatch.ColorIndex = 70;
                                }
                                else if (acHatchValue1 > -65 && acHatchValue1 <= -55)
                                {
                                    acHatch.ColorIndex = 110;
                                }
                                else if (acHatchValue1 > -75 && acHatchValue1 <= -65)
                                {
                                    acHatch.ColorIndex = 120;
                                }
                                else if (acHatchValue1 > -85 && acHatchValue1 <= -75)
                                {
                                    acHatch.ColorIndex = 130;
                                }
                                else if (acHatchValue1 > -95 && acHatchValue1 <= -85)
                                {
                                    acHatch.ColorIndex = 140;
                                }
                                else if (acHatchValue1 > -105 && acHatchValue1 <= -95)
                                {
                                    acHatch.ColorIndex = 150;
                                }
                                else
                                {
                                    acHatch.ColorIndex = 160;
                                }
                                string acHatchValue1_1 = Convert.ToString(acHatchValue1);
                                string acHatchValue1_2 = Convert.ToString(acHatchValue2);
                                ResultBuffer resbHatch = new ResultBuffer(new TypedValue(1001, "Parameters"), new TypedValue(1000, acHatchValue1_1), new TypedValue(1000, acHatchValue1_2));
                                acHatch.XData = resbHatch;
                                resbHatch.Dispose();
                            }
                            acHatch.AppendLoop(HatchLoopTypes.Outermost, acPolyLineObjIdColl);
                            acHatch.EvaluateHatch(true);
                            acBlkTblRec.AppendEntity(acHatch);
                            acTrans.AddNewlyCreatedDBObject(acHatch, true);
                            acHatchObjIdCol.Add(acHatch.ObjectId);
                        }
                        acPolyline.Erase();
                    }
                    if (acHatchObjIdCol.Count > 0)
                    {
                        dot.MoveToBottom(acHatchObjIdCol);
                    }
                    pm.Stop();
                    acTrans.Commit();
                }
                using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
                {
                    BlockTable acBlkTbl;
                    acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId, OpenMode.ForWrite) as BlockTable;
                    // 以写方式打开模型空间块表记录   Open the Block table record Model space for write
                    BlockTableRecord acBlkTblRec;
                    acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;
                    foreach (ObjectId asObjId in acBlkTblRec)
                    {
                        Entity ent = acTrans.GetObject(asObjId, OpenMode.ForWrite, false) as Entity;
                        if (ent.Layer == Layerline || ent.Layer == LayerCircle||ent.Layer==LayerExplode)
                        {
                            ent.Erase();
                        }
                    }
                    acTrans.Commit();
                }
            }
        }

        //获得旋转后的点
        static Point2d PolarPoints(Point2d pPt, double dAng, double dDist)
        {
            return new Point2d(pPt.X + dDist * Math.Cos(dAng), pPt.Y + dDist * Math.Sin(dAng));
        }

        //获得路径衰减，f为频率 MHz，d为距离 Km
        static double GetDistanceAttenuation(double f, double d)
        {
            double Lbs = 0;
            //Lbs(dB) = 32.45 + 20lgf(MHz) + 20lgd(km)
            if (d > 0.00001)
            {
                Lbs = 32.45 + 20 * Math.Log10(f) + 20 * Math.Log10(d);
            }
            return Lbs;
        }

        //角度转换为弧度
        public static double ConvertDegreesToRadians(double degrees)
        {
            double radians = (Math.PI / 180) * degrees;
            return (radians);
        }

        // 调色板
        public void palette(Point3d ptStart, Point3d ptEnd)
        {
            Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Database acCurDb = acDoc.Database;
            Editor acDocEd = acDoc.Editor;
            string Layercolorboundary = "调色板";//存放边界框的图层
            using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
            {
                // 以只读方式打开块表记录   Open the Block table record for read
                BlockTable acBlkTbl;
                acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId, OpenMode.ForRead) as BlockTable;
                // 以写方式打开模型空间块表记录   Open the Block table record Model space for write
                BlockTableRecord acBlkTblRec;
                acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;
                LayerTable acLyrTbl;
                acLyrTbl = acTrans.GetObject(acCurDb.LayerTableId, OpenMode.ForRead) as LayerTable;
                
                // 画颜色注释
                if (acLyrTbl.Has(Layercolorboundary) == false)
                {
                    LayerTableRecord acLyrTblRec = new LayerTableRecord();
                    acLyrTblRec.Name = Layercolorboundary;
                    acLyrTbl.UpgradeOpen();
                    acLyrTbl.Add(acLyrTblRec);
                    acTrans.AddNewlyCreatedDBObject(acLyrTblRec, true);
                }
                // 颜色条长度和宽度
                double len = ptStart.Y - ptEnd.Y;
                double length = (len / 2) / 13;
                double dis = length / 2;
                double wid = ptEnd.X - ptStart.X;
                double width = wid / 20;
                // 单行文本的高度和位置设置
                double txtlen = length / 3;
                double txtposi = txtlen * 2;

                // 场强<-105 颜色160
                Point2d point10 = new Point2d(ptEnd.X + dis, ptStart.Y - length*1.5);
                Point2d point11 = new Point2d(point10.X, point10.Y - length);
                Point2d point12 = new Point2d(point10.X + width, point10.Y - length);
                Point2d point13 = new Point2d(point10.X + width, point10.Y);
                Polyline acPoly1 = new Polyline();
                acPoly1.SetDatabaseDefaults();
                acPoly1.AddVertexAt(0, point10, 0, 0, 0);
                acPoly1.AddVertexAt(1, point11, 0, 0, 0);
                acPoly1.AddVertexAt(2, point12, 0, 0, 0);
                acPoly1.AddVertexAt(3, point13, 0, 0, 0);
                acPoly1.AddVertexAt(4, point10, 0, 0, 0);
                acPoly1.Closed = true;
                acPoly1.Layer = Layercolorboundary;
                // 添加新对象到块表记录和事务中   Add the new object to the block table record and the transaction
                acBlkTblRec.AppendEntity(acPoly1);
                acTrans.AddNewlyCreatedDBObject(acPoly1, true);

                // Adds the arc and line to an object id collection
                ObjectIdCollection acObjIdColl1 = new ObjectIdCollection();
                acObjIdColl1.Add(acPoly1.ObjectId);


                // 创建图案填充对象并添加到块表记录中    Create the hatch object and append it to the block table record
                Hatch acHatch1 = new Hatch();
                acHatch1.Layer = Layercolorboundary;
                acBlkTblRec.AppendEntity(acHatch1);
                acTrans.AddNewlyCreatedDBObject(acHatch1, true);

                // Set the properties of the hatch object
                // Associative must be set after the hatch object is appended to the 
                // block table record and before AppendLoop
                acHatch1.SetDatabaseDefaults();
                acHatch1.SetHatchPattern(HatchPatternType.PreDefined, "SOLID");
                acHatch1.ColorIndex = 160;
                acHatch1.Associative = true;
                acHatch1.AppendLoop(HatchLoopTypes.Outermost, acObjIdColl1);

                //创建单行文本对象    Create a single-line text object
                DBText acText1 = new DBText();
                acText1.Layer = Layercolorboundary;
                acText1.SetDatabaseDefaults();
                acText1.Position = new Point3d(point10.X + dis/2 + width, point10.Y - txtposi, 0);
                acText1.Height = txtlen;
                acText1.TextString = "<-105dBm";

                acBlkTblRec.AppendEntity(acText1);
                acTrans.AddNewlyCreatedDBObject(acText1, true);

                // 场强-105< ≤-95，颜色150
                Point2d point20 = new Point2d(point11.X, point11.Y);
                Point2d point21 = new Point2d(point20.X, point20.Y - length);
                Point2d point22 = new Point2d(point20.X + width, point20.Y - length);
                Point2d point23 = new Point2d(point20.X + width, point20.Y);
                Polyline acPoly2 = new Polyline();
                acPoly2.SetDatabaseDefaults();
                acPoly2.AddVertexAt(0, point20, 0, 0, 0);
                acPoly2.AddVertexAt(1, point21, 0, 0, 0);
                acPoly2.AddVertexAt(2, point22, 0, 0, 0);
                acPoly2.AddVertexAt(3, point23, 0, 0, 0);
                acPoly2.AddVertexAt(4, point20, 0, 0, 0);
                acPoly2.Closed = true;
                acPoly2.Layer = Layercolorboundary;
                // 添加新对象到块表记录和事务中   Add the new object to the block table record and the transaction
                acBlkTblRec.AppendEntity(acPoly2);
                acTrans.AddNewlyCreatedDBObject(acPoly2, true);

                // Adds the arc and line to an object id collection
                ObjectIdCollection acObjIdColl2 = new ObjectIdCollection();
                acObjIdColl2.Add(acPoly2.ObjectId);


                // 创建图案填充对象并添加到块表记录中    Create the hatch object and append it to the block table record
                Hatch acHatch2 = new Hatch();
                acHatch2.Layer = Layercolorboundary;
                acBlkTblRec.AppendEntity(acHatch2);
                acTrans.AddNewlyCreatedDBObject(acHatch2, true);

                // Set the properties of the hatch object
                // Associative must be set after the hatch object is appended to the 
                // block table record and before AppendLoop
                acHatch2.SetDatabaseDefaults();
                acHatch2.SetHatchPattern(HatchPatternType.PreDefined, "SOLID");
                acHatch2.ColorIndex = 150;
                acHatch2.Associative = true;
                acHatch2.AppendLoop(HatchLoopTypes.Outermost, acObjIdColl2);

                //创建单行文本对象    Create a single-line text object
                DBText acText2 = new DBText();
                acText2.Layer = Layercolorboundary;
                acText2.SetDatabaseDefaults();
                acText2.Position = new Point3d(point20.X + dis / 2 + width, point20.Y - txtposi, 0);
                acText2.Height = txtlen;
                acText2.TextString = "[-105,-95]dBm";

                acBlkTblRec.AppendEntity(acText2);
                acTrans.AddNewlyCreatedDBObject(acText2, true);

                // 场强-95< ≤-85，颜色140
                Point2d point30 = new Point2d(point21.X, point21.Y);
                Point2d point31 = new Point2d(point30.X, point30.Y - length);
                Point2d point32 = new Point2d(point30.X + width, point30.Y - length);
                Point2d point33 = new Point2d(point30.X + width, point30.Y);
                Polyline acPoly3 = new Polyline();
                acPoly3.SetDatabaseDefaults();
                acPoly3.AddVertexAt(0, point30, 0, 0, 0);
                acPoly3.AddVertexAt(1, point31, 0, 0, 0);
                acPoly3.AddVertexAt(2, point32, 0, 0, 0);
                acPoly3.AddVertexAt(3, point33, 0, 0, 0);
                acPoly3.AddVertexAt(4, point30, 0, 0, 0);
                acPoly3.Closed = true;
                acPoly3.Layer = Layercolorboundary;
                // 添加新对象到块表记录和事务中   Add the new object to the block table record and the transaction
                acBlkTblRec.AppendEntity(acPoly3);
                acTrans.AddNewlyCreatedDBObject(acPoly3, true);

                // Adds the arc and line to an object id collection
                ObjectIdCollection acObjIdColl3 = new ObjectIdCollection();
                acObjIdColl3.Add(acPoly3.ObjectId);


                // 创建图案填充对象并添加到块表记录中    Create the hatch object and append it to the block table record
                Hatch acHatch3 = new Hatch();
                acHatch3.Layer = Layercolorboundary;
                acBlkTblRec.AppendEntity(acHatch3);
                acTrans.AddNewlyCreatedDBObject(acHatch3, true);

                // Set the properties of the hatch object
                // Associative must be set after the hatch object is appended to the 
                // block table record and before AppendLoop
                acHatch3.SetDatabaseDefaults();
                acHatch3.SetHatchPattern(HatchPatternType.PreDefined, "SOLID");
                acHatch3.ColorIndex = 140;
                acHatch3.Associative = true;
                acHatch3.AppendLoop(HatchLoopTypes.Outermost, acObjIdColl3);

                //创建单行文本对象    Create a single-line text object
                DBText acText3 = new DBText();
                acText3.Layer = Layercolorboundary;
                acText3.SetDatabaseDefaults();
                acText3.Position = new Point3d(point30.X + dis / 2 + width, point30.Y - txtposi, 0);
                acText3.Height = txtlen;
                acText3.TextString = "[-95,-85]dBm";

                acBlkTblRec.AppendEntity(acText3);
                acTrans.AddNewlyCreatedDBObject(acText3, true);


                // 场强-85< ≤-75，颜色130
                Point2d point40 = new Point2d(point31.X, point31.Y);
                Point2d point41 = new Point2d(point40.X, point40.Y - length);
                Point2d point42 = new Point2d(point40.X + width, point40.Y - length);
                Point2d point43 = new Point2d(point40.X + width, point40.Y);
                Polyline acPoly4 = new Polyline();
                acPoly4.SetDatabaseDefaults();
                acPoly4.AddVertexAt(0, point40, 0, 0, 0);
                acPoly4.AddVertexAt(1, point41, 0, 0, 0);
                acPoly4.AddVertexAt(2, point42, 0, 0, 0);
                acPoly4.AddVertexAt(3, point43, 0, 0, 0);
                acPoly4.AddVertexAt(4, point40, 0, 0, 0);
                acPoly4.Closed = true;
                acPoly4.Layer = Layercolorboundary;
                // 添加新对象到块表记录和事务中   Add the new object to the block table record and the transaction
                acBlkTblRec.AppendEntity(acPoly4);
                acTrans.AddNewlyCreatedDBObject(acPoly4, true);

                // Adds the arc and line to an object id collection
                ObjectIdCollection acObjIdColl4 = new ObjectIdCollection();
                acObjIdColl4.Add(acPoly4.ObjectId);


                // 创建图案填充对象并添加到块表记录中    Create the hatch object and append it to the block table record
                Hatch acHatch4 = new Hatch();
                acHatch4.Layer = Layercolorboundary;
                acBlkTblRec.AppendEntity(acHatch4);
                acTrans.AddNewlyCreatedDBObject(acHatch4, true);

                // Set the properties of the hatch object
                // Associative must be set after the hatch object is appended to the 
                // block table record and before AppendLoop
                acHatch4.SetDatabaseDefaults();
                acHatch4.SetHatchPattern(HatchPatternType.PreDefined, "SOLID");
                acHatch4.ColorIndex = 130;
                acHatch4.Associative = true;
                acHatch4.AppendLoop(HatchLoopTypes.Outermost, acObjIdColl4);

                //创建单行文本对象    Create a single-line text object
                DBText acText4 = new DBText();
                acText4.Layer = Layercolorboundary;
                acText4.SetDatabaseDefaults();
                acText4.Position = new Point3d(point40.X + dis / 2 + width, point40.Y - txtposi, 0);
                acText4.Height = txtlen;
                acText4.TextString = "[-85,-75]dBm";

                acBlkTblRec.AppendEntity(acText4);
                acTrans.AddNewlyCreatedDBObject(acText4, true);


                // 场强-75< ≤-65，颜色120
                Point2d point50 = new Point2d(point41.X, point41.Y);
                Point2d point51 = new Point2d(point50.X, point50.Y - length);
                Point2d point52 = new Point2d(point50.X + width, point50.Y - length);
                Point2d point53 = new Point2d(point50.X + width, point50.Y);
                Polyline acPoly5 = new Polyline();
                acPoly5.SetDatabaseDefaults();
                acPoly5.AddVertexAt(0, point50, 0, 0, 0);
                acPoly5.AddVertexAt(1, point51, 0, 0, 0);
                acPoly5.AddVertexAt(2, point52, 0, 0, 0);
                acPoly5.AddVertexAt(3, point53, 0, 0, 0);
                acPoly5.AddVertexAt(4, point50, 0, 0, 0);
                acPoly5.Closed = true;
                acPoly5.Layer = Layercolorboundary;
                // 添加新对象到块表记录和事务中   Add the new object to the block table record and the transaction
                acBlkTblRec.AppendEntity(acPoly5);
                acTrans.AddNewlyCreatedDBObject(acPoly5, true);

                // Adds the arc and line to an object id collection
                ObjectIdCollection acObjIdColl5 = new ObjectIdCollection();
                acObjIdColl5.Add(acPoly5.ObjectId);


                // 创建图案填充对象并添加到块表记录中    Create the hatch object and append it to the block table record
                Hatch acHatch5 = new Hatch();
                acHatch5.Layer = Layercolorboundary;
                acBlkTblRec.AppendEntity(acHatch5);
                acTrans.AddNewlyCreatedDBObject(acHatch5, true);

                // Set the properties of the hatch object
                // Associative must be set after the hatch object is appended to the 
                // block table record and before AppendLoop
                acHatch5.SetDatabaseDefaults();
                acHatch5.SetHatchPattern(HatchPatternType.PreDefined, "SOLID");
                acHatch5.ColorIndex = 120;
                acHatch5.Associative = true;
                acHatch5.AppendLoop(HatchLoopTypes.Outermost, acObjIdColl5);

                //创建单行文本对象    Create a single-line text object
                DBText acText5 = new DBText();
                acText5.Layer = Layercolorboundary;
                acText5.SetDatabaseDefaults();
                acText5.Position = new Point3d(point50.X + dis / 2 + width, point50.Y - txtposi, 0);
                acText5.Height = txtlen;
                acText5.TextString = "[-75,-65]dBm";

                acBlkTblRec.AppendEntity(acText5);
                acTrans.AddNewlyCreatedDBObject(acText5, true);


                // 场强-65< ≤-55，颜色110
                Point2d point60 = new Point2d(point51.X, point51.Y);
                Point2d point61 = new Point2d(point60.X, point60.Y - length);
                Point2d point62 = new Point2d(point60.X + width, point60.Y - length);
                Point2d point63 = new Point2d(point60.X + width, point60.Y);
                Polyline acPoly6 = new Polyline();
                acPoly6.SetDatabaseDefaults();
                acPoly6.AddVertexAt(0, point60, 0, 0, 0);
                acPoly6.AddVertexAt(1, point61, 0, 0, 0);
                acPoly6.AddVertexAt(2, point62, 0, 0, 0);
                acPoly6.AddVertexAt(3, point63, 0, 0, 0);
                acPoly6.AddVertexAt(4, point60, 0, 0, 0);
                acPoly6.Closed = true;
                acPoly6.Layer = Layercolorboundary;
                // 添加新对象到块表记录和事务中   Add the new object to the block table record and the transaction
                acBlkTblRec.AppendEntity(acPoly6);
                acTrans.AddNewlyCreatedDBObject(acPoly6, true);

                // Adds the arc and line to an object id collection
                ObjectIdCollection acObjIdColl6 = new ObjectIdCollection();
                acObjIdColl6.Add(acPoly6.ObjectId);


                // 创建图案填充对象并添加到块表记录中    Create the hatch object and append it to the block table record
                Hatch acHatch6 = new Hatch();
                acHatch6.Layer = Layercolorboundary;
                acBlkTblRec.AppendEntity(acHatch6);
                acTrans.AddNewlyCreatedDBObject(acHatch6, true);

                // Set the properties of the hatch object
                // Associative must be set after the hatch object is appended to the 
                // block table record and before AppendLoop
                acHatch6.SetDatabaseDefaults();
                acHatch6.SetHatchPattern(HatchPatternType.PreDefined, "SOLID");
                acHatch6.ColorIndex = 110;
                acHatch6.Associative = true;
                acHatch6.AppendLoop(HatchLoopTypes.Outermost, acObjIdColl6);

                //创建单行文本对象    Create a single-line text object
                DBText acText6 = new DBText();
                acText6.Layer = Layercolorboundary;
                acText6.SetDatabaseDefaults();
                acText6.Position = new Point3d(point60.X + dis / 2 + width, point60.Y - txtposi, 0);
                acText6.Height = txtlen;
                acText6.TextString = "[-65,-55]dBm";

                acBlkTblRec.AppendEntity(acText6);
                acTrans.AddNewlyCreatedDBObject(acText6, true);


                // 场强-55< ≤-45，颜色70
                Point2d point70 = new Point2d(point61.X, point61.Y);
                Point2d point71 = new Point2d(point70.X, point70.Y - length);
                Point2d point72 = new Point2d(point70.X + width, point70.Y - length);
                Point2d point73 = new Point2d(point70.X + width, point70.Y);
                Polyline acPoly7 = new Polyline();
                acPoly7.SetDatabaseDefaults();
                acPoly7.AddVertexAt(0, point70, 0, 0, 0);
                acPoly7.AddVertexAt(1, point71, 0, 0, 0);
                acPoly7.AddVertexAt(2, point72, 0, 0, 0);
                acPoly7.AddVertexAt(3, point73, 0, 0, 0);
                acPoly7.AddVertexAt(4, point70, 0, 0, 0);
                acPoly7.Closed = true;
                acPoly7.Layer = Layercolorboundary;
                // 添加新对象到块表记录和事务中   Add the new object to the block table record and the transaction
                acBlkTblRec.AppendEntity(acPoly7);
                acTrans.AddNewlyCreatedDBObject(acPoly7, true);

                // Adds the arc and line to an object id collection
                ObjectIdCollection acObjIdColl7 = new ObjectIdCollection();
                acObjIdColl7.Add(acPoly7.ObjectId);


                // 创建图案填充对象并添加到块表记录中    Create the hatch object and append it to the block table record
                Hatch acHatch7 = new Hatch();
                acHatch7.Layer = Layercolorboundary;
                acBlkTblRec.AppendEntity(acHatch7);
                acTrans.AddNewlyCreatedDBObject(acHatch7, true);

                // Set the properties of the hatch object
                // Associative must be set after the hatch object is appended to the 
                // block table record and before AppendLoop
                acHatch7.SetDatabaseDefaults();
                acHatch7.SetHatchPattern(HatchPatternType.PreDefined, "SOLID");
                acHatch7.ColorIndex = 70;
                acHatch7.Associative = true;
                acHatch7.AppendLoop(HatchLoopTypes.Outermost, acObjIdColl7);

                //创建单行文本对象    Create a single-line text object
                DBText acText7 = new DBText();
                acText7.Layer = Layercolorboundary;
                acText7.SetDatabaseDefaults();
                acText7.Position = new Point3d(point70.X + dis / 2 + width, point70.Y - txtposi, 0);
                acText7.Height = txtlen;
                acText7.TextString = "[-55,-45]dBm";

                acBlkTblRec.AppendEntity(acText7);
                acTrans.AddNewlyCreatedDBObject(acText7, true);


                // 场强-45< ≤-35，颜色60
                Point2d point80 = new Point2d(point71.X, point71.Y);
                Point2d point81 = new Point2d(point80.X, point80.Y - length);
                Point2d point82 = new Point2d(point80.X + width, point80.Y - length);
                Point2d point83 = new Point2d(point80.X + width, point80.Y);
                Polyline acPoly8 = new Polyline();
                acPoly8.SetDatabaseDefaults();
                acPoly8.AddVertexAt(0, point80, 0, 0, 0);
                acPoly8.AddVertexAt(1, point81, 0, 0, 0);
                acPoly8.AddVertexAt(2, point82, 0, 0, 0);
                acPoly8.AddVertexAt(3, point83, 0, 0, 0);
                acPoly8.AddVertexAt(4, point80, 0, 0, 0);
                acPoly8.Closed = true;
                acPoly8.Layer = Layercolorboundary;
                // 添加新对象到块表记录和事务中   Add the new object to the block table record and the transaction
                acBlkTblRec.AppendEntity(acPoly8);
                acTrans.AddNewlyCreatedDBObject(acPoly8, true);

                // Adds the arc and line to an object id collection
                ObjectIdCollection acObjIdCol8 = new ObjectIdCollection();
                acObjIdCol8.Add(acPoly8.ObjectId);


                // 创建图案填充对象并添加到块表记录中    Create the hatch object and append it to the block table record
                Hatch acHatch8 = new Hatch();
                acHatch8.Layer = Layercolorboundary;
                acBlkTblRec.AppendEntity(acHatch8);
                acTrans.AddNewlyCreatedDBObject(acHatch8, true);

                // Set the properties of the hatch object
                // Associative must be set after the hatch object is appended to the 
                // block table record and before AppendLoop
                acHatch8.SetDatabaseDefaults();
                acHatch8.SetHatchPattern(HatchPatternType.PreDefined, "SOLID");
                acHatch8.ColorIndex = 60;
                acHatch8.Associative = true;
                acHatch8.AppendLoop(HatchLoopTypes.Outermost, acObjIdCol8);

                //创建单行文本对象    Create a single-line text object
                DBText acText8 = new DBText();
                acText8.Layer = Layercolorboundary;
                acText8.SetDatabaseDefaults();
                acText8.Position = new Point3d(point80.X + dis / 2 + width, point80.Y - txtposi, 0);
                acText8.Height = txtlen;
                acText8.TextString = "[-45,-35]dBm";

                acBlkTblRec.AppendEntity(acText8);
                acTrans.AddNewlyCreatedDBObject(acText8, true);


                // 场强-35< ≤-25，颜色50
                Point2d point90 = new Point2d(point81.X, point81.Y);
                Point2d point91 = new Point2d(point90.X, point90.Y - length);
                Point2d point92 = new Point2d(point90.X + width, point90.Y - length);
                Point2d point93 = new Point2d(point90.X + width, point90.Y);
                Polyline acPoly9 = new Polyline();
                acPoly9.SetDatabaseDefaults();
                acPoly9.AddVertexAt(0, point90, 0, 0, 0);
                acPoly9.AddVertexAt(1, point91, 0, 0, 0);
                acPoly9.AddVertexAt(2, point92, 0, 0, 0);
                acPoly9.AddVertexAt(3, point93, 0, 0, 0);
                acPoly9.AddVertexAt(4, point90, 0, 0, 0);
                acPoly9.Closed = true;
                acPoly9.Layer = Layercolorboundary;
                // 添加新对象到块表记录和事务中   Add the new object to the block table record and the transaction
                acBlkTblRec.AppendEntity(acPoly9);
                acTrans.AddNewlyCreatedDBObject(acPoly9, true);

                // Adds the arc and line to an object id collection
                ObjectIdCollection acObjIdCol9 = new ObjectIdCollection();
                acObjIdCol9.Add(acPoly9.ObjectId);


                // 创建图案填充对象并添加到块表记录中    Create the hatch object and append it to the block table record
                Hatch acHatch9 = new Hatch();
                acHatch9.Layer = Layercolorboundary;
                acBlkTblRec.AppendEntity(acHatch9);
                acTrans.AddNewlyCreatedDBObject(acHatch9, true);

                // Set the properties of the hatch object
                // Associative must be set after the hatch object is appended to the 
                // block table record and before AppendLoop
                acHatch9.SetDatabaseDefaults();
                acHatch9.SetHatchPattern(HatchPatternType.PreDefined, "SOLID");
                acHatch9.ColorIndex = 50;
                acHatch9.Associative = true;
                acHatch9.AppendLoop(HatchLoopTypes.Outermost, acObjIdCol9);

                //创建单行文本对象    Create a single-line text object
                DBText acText9 = new DBText();
                acText9.Layer = Layercolorboundary;
                acText9.SetDatabaseDefaults();
                acText9.Position = new Point3d(point90.X + dis / 2 + width, point90.Y - txtposi, 0);
                acText9.Height = txtlen;
                acText9.TextString = "[-35,-25]dBm";

                acBlkTblRec.AppendEntity(acText9);
                acTrans.AddNewlyCreatedDBObject(acText9, true);


                // 场强-25< ≤-15，颜色40
                Point2d point100 = new Point2d(point91.X, point91.Y);
                Point2d point101 = new Point2d(point100.X, point100.Y - length);
                Point2d point102 = new Point2d(point100.X + width, point100.Y - length);
                Point2d point103 = new Point2d(point100.X + width, point100.Y);
                Polyline acPoly10 = new Polyline();
                acPoly10.SetDatabaseDefaults();
                acPoly10.AddVertexAt(0, point100, 0, 0, 0);
                acPoly10.AddVertexAt(1, point101, 0, 0, 0);
                acPoly10.AddVertexAt(2, point102, 0, 0, 0);
                acPoly10.AddVertexAt(3, point103, 0, 0, 0);
                acPoly10.AddVertexAt(4, point100, 0, 0, 0);
                acPoly10.Closed = true;
                acPoly10.Layer = Layercolorboundary;
                // 添加新对象到块表记录和事务中   Add the new object to the block table record and the transaction
                acBlkTblRec.AppendEntity(acPoly10);
                acTrans.AddNewlyCreatedDBObject(acPoly10, true);

                // Adds the arc and line to an object id collection
                ObjectIdCollection acObjIdCol10 = new ObjectIdCollection();
                acObjIdCol10.Add(acPoly10.ObjectId);


                // 创建图案填充对象并添加到块表记录中    Create the hatch object and append it to the block table record
                Hatch acHatch10 = new Hatch();
                acHatch10.Layer = Layercolorboundary;
                acBlkTblRec.AppendEntity(acHatch10);
                acTrans.AddNewlyCreatedDBObject(acHatch10, true);

                // Set the properties of the hatch object
                // Associative must be set after the hatch object is appended to the 
                // block table record and before AppendLoop
                acHatch10.SetDatabaseDefaults();
                acHatch10.SetHatchPattern(HatchPatternType.PreDefined, "SOLID");
                acHatch10.ColorIndex = 40;
                acHatch10.Associative = true;
                acHatch10.AppendLoop(HatchLoopTypes.Outermost, acObjIdCol10);

                //创建单行文本对象    Create a single-line text object
                DBText acText10 = new DBText();
                acText10.Layer = Layercolorboundary;
                acText10.SetDatabaseDefaults();
                acText10.Position = new Point3d(point100.X + dis / 2 + width, point100.Y - txtposi, 0);
                acText10.Height = txtlen;
                acText10.TextString = "[-25,-15]dBm";

                acBlkTblRec.AppendEntity(acText10);
                acTrans.AddNewlyCreatedDBObject(acText10, true);


                // 场强-15< ≤-5，颜色30
                Point2d point110 = new Point2d(point101.X, point101.Y);
                Point2d point111 = new Point2d(point110.X, point110.Y - length);
                Point2d point112 = new Point2d(point110.X + width, point110.Y - length);
                Point2d point113 = new Point2d(point110.X + width, point110.Y);
                Polyline acPoly11 = new Polyline();
                acPoly11.SetDatabaseDefaults();
                acPoly11.AddVertexAt(0, point110, 0, 0, 0);
                acPoly11.AddVertexAt(1, point111, 0, 0, 0);
                acPoly11.AddVertexAt(2, point112, 0, 0, 0);
                acPoly11.AddVertexAt(3, point113, 0, 0, 0);
                acPoly11.AddVertexAt(4, point110, 0, 0, 0);
                acPoly11.Closed = true;
                acPoly11.Layer = Layercolorboundary;
                // 添加新对象到块表记录和事务中   Add the new object to the block table record and the transaction
                acBlkTblRec.AppendEntity(acPoly11);
                acTrans.AddNewlyCreatedDBObject(acPoly11, true);

                // Adds the arc and line to an object id collection
                ObjectIdCollection acObjIdCol11 = new ObjectIdCollection();
                acObjIdCol11.Add(acPoly11.ObjectId);


                // 创建图案填充对象并添加到块表记录中    Create the hatch object and append it to the block table record
                Hatch acHatch11 = new Hatch();
                acHatch11.Layer = Layercolorboundary;
                acBlkTblRec.AppendEntity(acHatch11);
                acTrans.AddNewlyCreatedDBObject(acHatch11, true);

                // Set the properties of the hatch object
                // Associative must be set after the hatch object is appended to the 
                // block table record and before AppendLoop
                acHatch11.SetDatabaseDefaults();
                acHatch11.SetHatchPattern(HatchPatternType.PreDefined, "SOLID");
                acHatch11.ColorIndex = 30;
                acHatch11.Associative = true;
                acHatch11.AppendLoop(HatchLoopTypes.Outermost, acObjIdCol11);

                //创建单行文本对象    Create a single-line text object
                DBText acText11 = new DBText();
                acText11.Layer = Layercolorboundary;
                acText11.SetDatabaseDefaults();
                acText11.Position = new Point3d(point110.X + dis / 2 + width, point110.Y - txtposi, 0);
                acText11.Height = txtlen;
                acText11.TextString = "[-15,-5]dBm";

                acBlkTblRec.AppendEntity(acText11);
                acTrans.AddNewlyCreatedDBObject(acText11, true);


                // 场强-5< ≤5，颜色20
                Point2d point120 = new Point2d(point111.X, point111.Y);
                Point2d point121 = new Point2d(point120.X, point120.Y - length);
                Point2d point122 = new Point2d(point120.X + width, point120.Y - length);
                Point2d point123 = new Point2d(point120.X + width, point120.Y);
                Polyline acPoly112 = new Polyline();
                acPoly112.SetDatabaseDefaults();
                acPoly112.AddVertexAt(0, point120, 0, 0, 0);
                acPoly112.AddVertexAt(1, point121, 0, 0, 0);
                acPoly112.AddVertexAt(2, point122, 0, 0, 0);
                acPoly112.AddVertexAt(3, point123, 0, 0, 0);
                acPoly112.AddVertexAt(4, point120, 0, 0, 0);
                acPoly112.Closed = true;
                acPoly112.Layer = Layercolorboundary;
                // 添加新对象到块表记录和事务中   Add the new object to the block table record and the transaction
                acBlkTblRec.AppendEntity(acPoly112);
                acTrans.AddNewlyCreatedDBObject(acPoly112, true);

                // Adds the arc and line to an object id collection
                ObjectIdCollection acObjIdCol12 = new ObjectIdCollection();
                acObjIdCol12.Add(acPoly112.ObjectId);


                // 创建图案填充对象并添加到块表记录中    Create the hatch object and append it to the block table record
                Hatch acHatch12 = new Hatch();
                acHatch12.Layer = Layercolorboundary;
                acBlkTblRec.AppendEntity(acHatch12);
                acTrans.AddNewlyCreatedDBObject(acHatch12, true);

                // Set the properties of the hatch object
                // Associative must be set after the hatch object is appended to the 
                // block table record and before AppendLoop
                acHatch12.SetDatabaseDefaults();
                acHatch12.SetHatchPattern(HatchPatternType.PreDefined, "SOLID");
                acHatch12.ColorIndex = 20;
                acHatch12.Associative = true;
                acHatch12.AppendLoop(HatchLoopTypes.Outermost, acObjIdCol12);

                //创建单行文本对象    Create a single-line text object
                DBText acText12 = new DBText();
                acText12.Layer = Layercolorboundary;
                acText12.SetDatabaseDefaults();
                acText12.Position = new Point3d(point120.X + dis / 2 + width, point120.Y - txtposi, 0);
                acText12.Height = txtlen;
                acText12.TextString = "[-5,5]dBm";

                acBlkTblRec.AppendEntity(acText12);
                acTrans.AddNewlyCreatedDBObject(acText12, true);


                // 场强5< ≤15，颜色10
                Point2d point130 = new Point2d(point121.X, point121.Y);
                Point2d point131 = new Point2d(point130.X, point130.Y - length);
                Point2d point132 = new Point2d(point130.X + width, point130.Y - length);
                Point2d point133 = new Point2d(point130.X + width, point130.Y);
                Polyline acPoly113 = new Polyline();
                acPoly113.SetDatabaseDefaults();
                acPoly113.AddVertexAt(0, point130, 0, 0, 0);
                acPoly113.AddVertexAt(1, point131, 0, 0, 0);
                acPoly113.AddVertexAt(2, point132, 0, 0, 0);
                acPoly113.AddVertexAt(3, point133, 0, 0, 0);
                acPoly113.AddVertexAt(4, point130, 0, 0, 0);
                acPoly113.Closed = true;
                acPoly113.Layer = Layercolorboundary;
                // 添加新对象到块表记录和事务中   Add the new object to the block table record and the transaction
                acBlkTblRec.AppendEntity(acPoly113);
                acTrans.AddNewlyCreatedDBObject(acPoly113, true);

                // Adds the arc and line to an object id collection
                ObjectIdCollection acObjIdCol13 = new ObjectIdCollection();
                acObjIdCol13.Add(acPoly113.ObjectId);


                // 创建图案填充对象并添加到块表记录中    Create the hatch object and append it to the block table record
                Hatch acHatch13 = new Hatch();
                acHatch13.Layer = Layercolorboundary;
                acBlkTblRec.AppendEntity(acHatch13);
                acTrans.AddNewlyCreatedDBObject(acHatch13, true);

                // Set the properties of the hatch object
                // Associative must be set after the hatch object is appended to the 
                // block table record and before AppendLoop
                acHatch13.SetDatabaseDefaults();
                acHatch13.SetHatchPattern(HatchPatternType.PreDefined, "SOLID");
                acHatch13.ColorIndex = 10;
                acHatch13.Associative = true;
                acHatch13.AppendLoop(HatchLoopTypes.Outermost, acObjIdCol13);

                //创建单行文本对象    Create a single-line text object
                DBText acText13 = new DBText();
                acText13.Layer = Layercolorboundary;
                acText13.SetDatabaseDefaults();
                acText13.Position = new Point3d(point130.X + width + dis / 2, point130.Y - txtposi, 0);
                acText13.Height = txtlen;
                acText13.TextString = "[5,15]dBm";

                acBlkTblRec.AppendEntity(acText13);
                acTrans.AddNewlyCreatedDBObject(acText13, true);


                acTrans.Commit();
            }
        }

        // 楼层名
        public void FloorName(Point3d ptStart, Point3d ptEnd, string str)
        {
            Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Database acCurDb = acDoc.Database;
            Editor acDocEd = acDoc.Editor;
            string LayerFloorboundary = "楼层名";//存放楼层名的图层
            try
            {
                using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
                {
                    // 以只读方式打开块表记录   Open the Block table record for read
                    BlockTable acBlkTbl;
                    acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId, OpenMode.ForRead) as BlockTable;
                    // 以写方式打开模型空间块表记录   Open the Block table record Model space for write
                    BlockTableRecord acBlkTblRec;
                    acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;
                    LayerTable acLyrTbl;
                    acLyrTbl = acTrans.GetObject(acCurDb.LayerTableId, OpenMode.ForRead) as LayerTable;

                    // 写楼层名
                    if (acLyrTbl.Has(LayerFloorboundary) == false)
                    {
                        LayerTableRecord acLyrTblRec = new LayerTableRecord();
                        acLyrTblRec.Name = LayerFloorboundary;
                        acLyrTbl.UpgradeOpen();
                        acLyrTbl.Add(acLyrTblRec);
                        acTrans.AddNewlyCreatedDBObject(acLyrTblRec, true);
                    }
                    // 颜色条长度和宽度
                    double len = ptStart.Y - ptEnd.Y;
                    double length = (len / 2) / 13;
                    // 单行文本的高度和位置设置
                    double dis = length / 2;
                    double wid = ptEnd.X - ptStart.X;
                    double width = wid / 20;
                    double txtlen = length / 1.5;
                    double txtposi = txtlen * 5;
                    //创建单行文本对象    Create a single-line text object
                    DBText acText = new DBText();
                    acText.Layer = LayerFloorboundary;
                    acText.SetDatabaseDefaults();
                    acText.Position = new Point3d(ptEnd.X + dis * 1.5, ptStart.Y - length, 0);
                    acText.Height = txtlen;
                    acText.TextString = str;
                    acText.TextStyleId = AddTextStyle("宋体", "1", "3");
                    acBlkTblRec.AppendEntity(acText);
                    acTrans.AddNewlyCreatedDBObject(acText, true);

                    acTrans.Commit();
                }
            }
            catch
            {
                using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
                {
                    // 以只读方式打开块表记录   Open the Block table record for read
                    BlockTable acBlkTbl;
                    acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId, OpenMode.ForRead) as BlockTable;
                    // 以写方式打开模型空间块表记录   Open the Block table record Model space for write
                    BlockTableRecord acBlkTblRec;
                    acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;
                    LayerTable acLyrTbl;
                    acLyrTbl = acTrans.GetObject(acCurDb.LayerTableId, OpenMode.ForRead) as LayerTable;

                    // 写楼层名
                    if (acLyrTbl.Has(LayerFloorboundary) == false)
                    {
                        LayerTableRecord acLyrTblRec = new LayerTableRecord();
                        acLyrTblRec.Name = LayerFloorboundary;
                        acLyrTbl.UpgradeOpen();
                        acLyrTbl.Add(acLyrTblRec);
                        acTrans.AddNewlyCreatedDBObject(acLyrTblRec, true);
                    }
                    // 颜色条长度和宽度
                    double len = ptStart.Y - ptEnd.Y;
                    double length = (len / 2) / 13;
                    // 单行文本的高度和位置设置
                    double dis = length / 2;
                    double wid = ptEnd.X - ptStart.X;
                    double width = wid / 20;
                    double txtlen = length / 1.5;
                    double txtposi = txtlen * 5;
                    //创建单行文本对象    Create a single-line text object
                    DBText acText = new DBText();
                    acText.Layer = LayerFloorboundary;
                    acText.SetDatabaseDefaults();
                    acText.Position = new Point3d(ptEnd.X + dis * 1.5, ptStart.Y - length, 0);
                    acText.Height = txtlen;
                    acText.TextString = str;
                    //acText.TextStyleId = AddTextStyle("宋体", "1", "3");
                    acBlkTblRec.AppendEntity(acText);
                    acTrans.AddNewlyCreatedDBObject(acText, true);

                    acTrans.Commit();
                }
            }
        }
        //建立文字样式
        public static ObjectId AddTextStyle(string name, string smallfont, string bigfont)
        {
            Database dbH = HostApplicationServices.WorkingDatabase;

            using (Transaction trans = dbH.TransactionManager.StartTransaction())
            {
                TextStyleTable TST = (TextStyleTable)trans.GetObject(dbH.TextStyleTableId, OpenMode.ForWrite);
                ObjectId id =  GetIdFromSymbolTable(TST, name);
                if (id == ObjectId.Null)
                {
                    TextStyleTableRecord TSTR = new TextStyleTableRecord();
                    TSTR.Name = name;
                    TSTR.FileName = smallfont;
                    TSTR.BigFontFileName = bigfont;
                    
                    //TSTR.TextSize = height;
                    //TSTR.XScale = xscale;
                    TST.UpgradeOpen();
                    id = TST.Add(TSTR);
                    trans.AddNewlyCreatedDBObject(TSTR, true);
                }
                return id;
            }
        }

        //取得符号表的Id
        public static ObjectId GetIdFromSymbolTable(SymbolTable st, string key)
        {
            Database dbH = HostApplicationServices.WorkingDatabase;
            using (Transaction trans = dbH.TransactionManager.StartTransaction())
            {
                if (st.Has(key))
                {
                    ObjectId idres = st[key];
                    if (!idres.IsErased)
                        return idres;
                    foreach (ObjectId id in st)
                    {
                        if (!id.IsErased)
                        {
                            SymbolTableRecord str = (SymbolTableRecord)trans.GetObject(id, OpenMode.ForRead);
                            if (str.Name == key)
                                return id;
                        }
                    }
                }
            }
            return ObjectId.Null;
        }

        // 鼠标悬停提示场强和频率
        Editor ed = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;
        [CommandMethod("TestOn")]
        public void MyTestOn1()
        {
            ed.PointMonitor += new PointMonitorEventHandler(ed_PointMonitor);
        }
        [CommandMethod("TestOff")]
        public void MyTestOff()
        {
            ed.PointMonitor -= new PointMonitorEventHandler(ed_PointMonitor);
        }
        void ed_PointMonitor(object sender, PointMonitorEventArgs e)
        {
            Database db = HostApplicationServices.WorkingDatabase;
            InputPointContext ipc = e.Context;
            FullSubentityPath[] ePaths = ipc.GetPickedEntities();
            if (ePaths.Length > 0)
            {
                FullSubentityPath ePath = ePaths[0];
                using (Transaction trans = db.TransactionManager.StartTransaction())
                {
                    ObjectId entId = ePath.GetObjectIds()[0];
                    Entity ent = (Entity)trans.GetObject(entId, OpenMode.ForRead);

                    var rb = ent.GetXDataForApplication("Parameters");//提取射线中的参数，查看其场强和频率
                    if (rb != null)
                    {
                        List<TypedValue> values = rb.Cast<TypedValue>().ToList();
                        string value_1 = Convert.ToString(values[1].Value);//读取该条射线的场强，并把其转换为整型
                        string value_2 = Convert.ToString(values[2].Value);//读取该条射线的频率
                        //减少场强小数点后位数
                        string []svalue_1 = value_1.Split('.');
                        //string shvalue_1="";
                        if (svalue_1.Count() == 2 && svalue_1[1].Length>4)
                        {

                            string shvalue_1 = svalue_1[0] + "." + svalue_1[1].Remove(4);
                            e.AppendToolTipText("\n场强：" + shvalue_1 + "\n频率：" + value_2);
                        }
                        else
                        {
                            e.AppendToolTipText("\n场强：" + value_1 + "\n频率：" + value_2);
                        }
                        //e.AppendToolTipText("\n场强：" + value_1 + "\n频率：" + value_2);
                    }
                    trans.Commit();
                }
            }
        }
    }
}
